net*_*ica 5 javascript prototypal-inheritance
我对以下代码的期望是,如果我检查a.name,它将搜索原型并在声明时返回它.任何人都可以确定是什么阻止JS承认我的原型?
var obj = function(parent){
return {
prototype: parent
}
};
var me = { name: 'keith' };
var a = new obj(me)
// => undefined
a.name
// => undefined
a.prototype.name
// => "keith"
Run Code Online (Sandbox Code Playgroud)
名为“prototype”的属性只是一个属性,它并不指向该对象继承的对象。使用Object.getPrototypeOf或非标准__proto__属性来获得它。
因此,您的函数obj(me)返回的只是一个具有属性“prototype”的对象,该对象指向具有属性“name”的对象,该属性指向 string keith。new当你的函数返回一个对象时,无论是否使用关键字调用它都没有区别。
对于继承来说,构造函数[object]的“prototype”属性是值得关注的。此构造函数(不返回对象)使用关键字创建的每个对象都继承自构造new函数的“prototype”属性所指向的对象。所以你可以这样做:
var Constructor = function() {
console.log(this); // logs the currently created object
// return nothing
}
Constructor.prototype = { name: 'keith' };
var a = new Constructor(); // logs an empty object
Object.getPrototypeOf(a) === Constructor.prototype; // true
a.name; // "keith" - inherited
Run Code Online (Sandbox Code Playgroud)