我期望从下面的代码将是,如果我检查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"My expectation from the following code would be that if I checked a.name, it would search the prototype and return it as it was declared. Can anyone pinpoint what it is that is preventing JS from acknowledging my prototype?
var obj = function(parent){ return { prototype: parent } }; var me = { name: 'keith' }; var a = new obj(me) // => undefined a.name // => undefined a.prototype.name // => "keith"最满意答案
名为“prototype”的属性只是一个属性,并不指向该对象从中继承的对象。 使用Object.getPrototypeOf或非标准的__proto__属性来获取它。
所以你的函数obj(me)返回的只是一个带有属性“prototype”的对象,它指向一个具有指向字符串keith的属性“name”的对象。 当你的函数返回一个对象时,用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" - inheritedA property named "prototype" is just a property, it does not point to the object from which the object inherits. Use Object.getPrototypeOf or the non-standard __proto__ property to get that.
So what your function obj(me) returns is just an object with a property "prototype" which points to an object with a property "name" which points to the string keith. As your function returns an object, it makes no difference whether it is called with the new keyword or not.
For inheritance, the "prototype" property of the constructor function [object] is of concern. Every object created by this constructor (which does not return an object) with the new keyword inherits from the object to which the "prototype" property of the constructor points. So you could do this:
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更多推荐
发布评论