简体   繁体   English

在此示例中使用继承的最有效方法?

[英]Most efficient way to use inheritance in this example?

So I've been messing around with some JavaScript inheritance techniques and here's one case in which I'm trying to derive a strong solution. 因此,我一直在搞弄一些JavaScript继承技术,在这种情况下,我试图得出一个强大的解决方案。

Here's a simple example: http://jsfiddle.net/JgrYu/ 这是一个简单的示例: http : //jsfiddle.net/JgrYu/

The Issue: Logically we'd expect the two div's to be both 0's. 问题:从逻辑上讲,我们希望两个div都为0。 But since we're just newing the extended class we don't re-generate our "c" variable. 但是由于我们只是在扩展扩展类,所以我们不会重新生成“ c”变量。

A potential fix for this is to use Functional inheritance: http://jsfiddle.net/h8xtz/ 一个可能的解决方法是使用函数继承: http : //jsfiddle.net/h8xtz/

function mybase() {
    var that = {};
    var c = 0;

    that.hi = function() {
        var ele = $('<div></div>');
        ele.html(c++);
        $('body').append(ele);
    }

    return that;
}

function myextended() {
    var that = mybase();

    that.hi();

    return that;
}

myextended.prototype = new mybase();

$(document).ready(function() {
    var a = myextended();
    var b = myextended();
})​

However the issue with this is that we clutter the global namespace and each object duplicates the functional properties when in reality we just want duplication of the private variables. 但是 ,这样做的问题是,当我们只想复制私有变量时,我们会使全局名称空间混乱,并且每个对象都复制了功能属性。

So, what I'm looking for is a better approach than functional inheritance to solve this issue. 因此,我正在寻找一种比函数继承更好的方法来解决此问题。 I've thought about making a psuedo classical inheritance structure where I separate the private and public variables/functions but I haven't been able to come up with a version with less overhead than the functional inheritance. 我曾经考虑过要建立一个伪经典的继承结构,在该结构中我将私有变量和公共变量/函数分开,但是我一直无法提供一个比函数继承少开销的版本。

If you want to create a new set of private variables for each object, you will need to call the parent's constructor from the child's one. 如果要为每个对象创建一组新的私有变量,则需要从子对象的父对象中调用父对象的构造函数。 And don't use a instance of the parent as the prototype object for the child, but just an object that inherits from the parent's prototype object. 并且不要将父对象的实例用作子对象的原型对象,而应仅使用从父对象的原型对象继承的对象。 This can be done with Object.create : 这可以通过Object.create完成:

function myextended() {
    mybase.call(this); // apply the parent's constructor on the new object
    this.hi();
}

myextended.prototype = Object.create(mybase.prototype);

( Demo ) 演示

How about making the variable a part of the prototype: 如何使变量成为原型的一部分:

function mybase() {

    this.hi = function() {
        var ele = $('<div></div>');
        ele.html(this.c++);
        $('body').append(ele);
    }
}

mybase.prototype.c = 0;

Here's the updated fiddle . 这是更新的小提琴

Note: Alternatively you could initialize this.c when declaring mybase. 注意:另外,您可以在声明mybase时初始化this.c

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

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