1、MDN 对 new 运算符的描述:
new
运算符创建一个用户定义的对象类型的实例或具有构造函数的内置对象的实例。new
关键字会进行如下操作:
- 创建一个空的简单的
JavaScript
对象(即{}
); - 链接该对象(即设置对象构造函数)到另一个对象;
- 将步骤1新创建的对象作为
this
的上下文; - 如果该函数没有返回对象,则返回
this
;
看个例子:
function Person(name,age) {
this.name = name;
this.age = age;
this.habit = 'Games';
}
Person.prototype.strength = 60;
Person.prototype.sayName = function () {
console.log('my name is '+this.name);
}
var person = new Person('Decun',28);
console.log(person.name);//Decun
console.log(person.habit);//Games
console.log(person.strength);//60
person.sayName();//my name is Decun
从这个例子可以看到,实例person
可以:
- 访问到
Person
构造函数里的属