Javascript原型怪癖

编程入门 行业动态 更新时间:2024-10-26 06:32:49
Javascript原型怪癖 - 任何人都可以解释一下吗?(Javascript Prototype Quirk - Can Anyone Explain This?)

我期望从下面的代码将是,如果我检查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" - inherited

A 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

更多推荐

本文发布于:2023-07-05 07:49:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1034851.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:怪癖   原型   Javascript

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!