new 创建对象发生了什么
2019-12-19 本文已影响0人
苦苦修行
参考自:new创建对象的过程发生了什么
示例代码:
function Person(name) {
this.name = name;
}
Person.hairColor = "black";
Person.prototype.say = function() {
console.log("My name is " + this.name);
};
var john = new Person("John");
console.log(
john.name, // "John",
john.hairColor, // undefined
john.height // undefined
);
john.say(); // "My name is John"
console.log(
Person.name, // "Person"
Person.hairColor // "black"
);
Person.say(); // Person.say is not a function
解析:
var john = new Person("John") = {
var obj = {};
obj.__proto__ = Person.prototype; // 此时便建立了obj对象的原型链:
// obj->Person.prototype->Object.prototype->null
var result = Person.call(obj,"John"); // 相当于obj.Person("John")
return typeof result === 'object' ? result : obj; // 如果无返回值或者返回一个非对象值,则将obj返回作为新对象
}