Я хочу наследовать от Button прототипом. Но предупрежденное имя остается "Сарой", поскольку это последний Созданный Ребенок. Класс Creator должен установить имя с помощью кнопки "Метод в кнопке". 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();
Это должно помочь вам начать:
(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();
})();
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;
});