Javascript:原型属性在父级上不可见 [英] Javascript: prototype attribute not visible on parent

查看:39
本文介绍了Javascript:原型属性在父级上不可见的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从这里获取的示例:http://sporto.github.io/blog/2013/02/22/a-plain-english-guide-to-javascript-prototypes/

我在这里也问了一个类似的问题:Javascript:添加的函数没有出现在父对象上.

I also asked a similar question here: Javascript: Added function does not appear on parent object.

创建对象

>function Person(name) {
    this.name = name;
}

添加一个属性作为原型.新的 kind 属性不会出现在对象上.

Add an attribute as a prototype. The new kind attribute does not appear on the object.

>Person.prototype.kind = 'person'

>Person
<function Person(name) {
    this.name = name;
}

现在使用父对象作为原型创建一个新对象.添加的属性可见.

Now create a new object using the parent as the prototype. The added attribute is visible.

var zack = new Person('Zack');

Person {name: "Zack", kind: "person"}

为什么添加的 kind 属性在父 Person 对象上不可见,即使它可以传达给子对象?

Why is the added kind attribute not visible on the parent Person object, even though it can convey it to children?

推荐答案

这是因为 Person 只是一个函数(对象)/构造函数:

This is beceause Person is just a funtion(object)/Constructor:

Person =
function Person(name) {
    this.name = name;
}

获取人物的实物请参考原型

To Get the kind object on person refer to the prototype

Person.prototype =
Person {kind: "person"}

我不是这方面的专家,但如果您想创建一个新的构造函数,您应该覆盖该函数.

Im not an expert in this but if you would want to create a new constructor you should overwrite the function.

您可以将函数(如下)视为设置实例特定变量的构造函数

You could see the function (below) as an constructor to set instance specific variables

    function Person(name) {
        this.name = name;
    }

Person.prototype.kind = 'person' 就像类上的静态变量

这篇关于Javascript:原型属性在父级上不可见的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆