JavaScript OOP:对象更改其原型(对于使用同一原型的所有其他对象) [英] JavaScript OOP: Objects change their prototype (for all other objects using the same prototype)

查看:51
本文介绍了JavaScript OOP:对象更改其原型(对于使用同一原型的所有其他对象)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

function NamedRoundedBlock(){
    var name = this.makeFeild("name");
    name.className = "Block NamedRound name";
    this.element.className = "Block NamedRound root";
    this.element.appendChild(name);
}
NamedRoundedBlock.prototype = new Block();
NamedRoundedBlock.prototype.constructor = NamedRoundedBlock;

有代码,有人知道我做错了吗?

There's the code, anyone know what I've done wrong?

我的问题是,如果我创建两个NamedRoundedBlock对象并更改一个对象的this.element属性(通过更改属性或其他内容),另一个对象的属性也会更改.

My problem is that if I make two NamedRoundedBlock objects and change the this.element property of one (by changing an attribute or something) the other's will change too.

此外,在Block中设置了this.makeFeildthis.element的更多详细信息

Also, a little additional detail, this.makeFeild and this.element are both set in Block

推荐答案

查看 JavaScript中的传统OOP继承

以上博客文章可能有助于回答您的一些问题.

The above blog post may help answer some of your questions.

它特别详细说明了为对象定义一个新的构造函数,该构造函数是从父对象继承"的.这是您的问题之一吗?以这个为例:

It elaborates particularly on defining a new constructor for an object, which "inherits" from a parent. Is that one of your questions? Take this for example:

NamedRoundedBlock.prototype = Object.create(
    Block.prototype,
        {
            "constructor": { 
                configurable: true,
                enumerable: false,
                writable: true,
                value: 'NamedRoundedBlock'
            }
        }
);

上面的代码基于 Block 的原型创建了一个对象,但它定义了自己的构造函数,并将其设置为不可枚举.

The above created an object based on Block's prototype, but it defines its own constructor, and also sets it as not enumerable.

还,第一行应该是这样吗?:

Also, should the first line be something like this?:

function NamedRoundedBlock() {
    this.name = this.makeFeild("name");
    //etc.

此外,与问题无关,我对"Feild"(拼写为"Field")的拼写要小心,因为拼写问题有时会在代码的后面引起难以发现的错误.

Additionally, independent of the issue, I'd be careful with the spelling of "Feild" (spelled "Field"), as spelling issues can sometimes cause hard-to-find bugs later in the code.

这篇关于JavaScript OOP:对象更改其原型(对于使用同一原型的所有其他对象)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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