new关键字与构造函数一起使用以创建对象:
function Employee(name, position, yearHired) {
this. name = name;
this. position = position;
this. yearHired = yearHired;
};
const emp = new Employee("Marko Polo", "Software Developer", 2017);
new关键字做了 4件事:
1、 创建空对象{}
2、 将空对象分配给this值
3、 将空对象的_ roto_指向构造函数的prototype
4、 如果没有使用显式return语句,则返回this

看下面事例:
function Person() { this. name = ‘kyle’ }
根据上面描述的,new Person()做了:
1、 创建一个空对象:var obj = {}
2、 将空对象分配给this值:this = obj
3、 将空对象的_ roto_指向构造函数的 prototype: this. __ roto_ = Person (). prototype
4、 返回 this:return this

Was this helpful?

0 / 0

发表回复 0

Your email address will not be published.