继承并重用对象oop

时间:2013-12-03 15:03:20

标签: javascript jquery oop

我想从原型继承Button。但警告名称保持“莎拉”,因为它是最后一个孩子创建。创建者类应使用按钮中的方法设置名称。 Jsfiddle:JSFIDDLE

function Creator() {
    var c1 = new Child();
    c1.SetName("Albert");
    c1.SetStandardClickHandler();

    var c2 = new Child();
    c2.SetStandardClickHandler();
    c2.SetName("Sarah");
}

Child.prototype = new Button();

function Child() {
    this._layout = $('<div>child</div>');
}

function Button() {
    var that = this;
    var _name;

    this.SetName = function (name) {
        _name = name;
    }
    this.SetStandardClickHandler = function () {
        this._layout.click(function () {
            alert(_name);
        });
    };
}

var c = new Creator();

2 个答案:

答案 0 :(得分:0)

var _name是一个静态变量。

尝试这样的事情:

function Button() {
    var that = this;
    this.name = null;

    this.SetName = function (name) {
        this.name = name;
    }
    this.SetStandardClickHandler = function () {
        this._layout.click(function () {
            alert(that.name);
        });
    };
}

或者您可以重组为以下内容:

var Button = (function() {

    function Button() {
        this.name = null;
    }

    Button.prototype.SetName = function (name) {
        this.name = name;
    }

    Button.prototype.SetStandardClickHandler = function () {
        var that = this;
        this._layout.click(function () {
            alert(that.name);
        });
    };

    return Button;
});

答案 1 :(得分:0)

这应该让你开始:

(function() {

    'use strict';

    var Button = function (name) {
        this.name = name || ''; // Set name to contructor value or empty string
    };

    Button.prototype.setName = function (name) {
        this.name = name;
    };

    Button.prototype.setDefaultClickListener = function () {
        this._layout.click(function () {
            alert(this.name);
        }.bind(this));
    };

    var Child = function (name) {
        Button.call(this, name); // Call parent object construtor on new instance of Child

        this._layout = $('<div>child</div>');
    };

    Child.prototype = Object.create(Button.prototype); // Inherit from Button prototype
    Child.prototype.constructor = Child; // Reset constructor to Child

    var albert = new Child('Albert');
    albert.setDefaultClickListener();

    var sarah = new Child('Sarah');
    sarah.setDefaultClickListener();

})();