简体   繁体   English

JavaScript中的原型对象继承

[英]Prototypical object inheritance in javascript

So I have this example that I have created and I have a question about why my child object is behaving the way it is. 因此,我有一个已创建的示例,但我有一个问题要问为什么子对象的行为方式如此。 I am creating a Cat object and creating an instance of that object names Kat. 我正在创建一个Cat对象,并创建一个名为Kat的对象的实例。 I am then using the object() method below to extend Kat to create an object called Poe . 然后,我使用下面的object()方法扩展Kat来创建一个名为Poe的对象。

function object(o) {
    function f() {};
    f.prototype = o;
    return new f();
}

My question is why does Poe seem to share private instance var and methods with Kat, even when Poe's public vars have been overwritten? 我的问题是,即使Poe的公共变量已被覆盖,但Poe为何似乎与Kat共享私有实例变量和方法? Also, these public methods work fine with the prototype public methods. 而且,这些公共方法可以与原型公共方法配合使用。

http://jsfiddle.net/ka_tee_jean/5aPT2/ http://jsfiddle.net/ka_tee_jean/5aPT2/

Setting the prototype will cause the new object to delegate to the one passed in for properties not defined in it. 设置原型将使新对象委托给传递给其中未定义属性的对象。 The constructor doesn't run for the child object, so it will initially have some undefined variables: 构造函数不会针对子对象运行,因此它最初将具有一些未定义的变量:

function object(o) {
    function f() {};
    f.prototype = o;
    return new f();
}

var object1 = { a: 1 };
var object2 = object(object1);

object1.a = 2
console.log(object2.a); // 2

If you want independent properties, then you need to copy them like: 如果需要独立的属性,则需要像下面这样复制它们:

function object(o) {
    var newObj = {};
    for(var key in o) {
        newObj[key] = o[key];
    }
    return newObj;
}

But the private instance variables are being accessed from a closure. 但是私有实例变量是从闭包中访问的。 Any copy of the same function will use the same private variable. 相同功能的任何副本都将使用相同的私有变量。 You would need use something like that.is_bored = 0 to define the variables instead. 您将需要使用that.is_bored = 0这样的变量来定义变量。

You may also want to look into changing your current Cat function into an true object. 您可能还需要考虑将当前的Cat函数更改为真实的对象。 By having it as a function you are blending classical inheritance with prototypical. 通过将其作为功能,您可以将经典继承与原型融合在一起。 Remember your current prototypical clone function (which you've labeled object) will create a new Class for you, hence the 请记住,您当前的原型克隆函数(已将其标记为object)将为您创建一个新的Class。

return new f();

Here is an example of how I would rewrite this to better follow prototypical inheritance design patterns. 这是一个示例,我将如何重写它以更好地遵循原型继承设计模式。

http://jsfiddle.net/scottcarlson/Dfnn3/2/ http://jsfiddle.net/scottcarlson/Dfnn3/2/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM