原型遗传的敲除问题

Knockout issue with prototypical inheritance

本文关键字:问题 原型      更新时间:2023-09-26

我在 Knockout 中遇到了一个问题,我在制作用户对象的原型时,我的对象的可观察属性似乎被最后一次出现覆盖了。

因此,我不能多次使用同一个对象,否则它将被覆盖。

虽然这很难解释,但请看我的小提琴。

http://jsfiddle.net/RSEcj/1/

我做错了什么?(或者这是淘汰赛中的一个错误?我该如何解决问题。

因为可观察量是函数而不是属性,所以它们由对象原型上的单个实例表示,这与设置时将在对象上创建的属性不同。

您可以使用函数继承来实现您想要的。

http://jsfiddle.net/ypWQN/1/

var User = function(firstName, lastName){
    var that = {};
    that.firstName = ko.observable(firstName);
    that.lastName = lastName;
    return that;
};

var Employee = function(firstName, lastName){
    var that = User();
    that.firstName(firstName);
    that.lastName = lastName; 
    return that;
};

希望这有帮助。

这里有一个不错的解决方案:http://jsfiddle.net/magikMaker/RSEcj/19/

它使用新方法inheritsFrom(),为此的功劳转到 http://phrogz.net/js/classes/OOPinJS2.html

将其与apply()方法和init()方法相结合,神奇的事情发生了... :-)

var Person = function(firstName, lastName){
    this.init = function(firstName, lastName){
        this.firstName = ko.observable(firstName);
        this.setLastName(lastName);
    };
    this.setLastName = function(lastName){
        this.lastName = lastName;
    };
    this.init.apply(this, arguments);
};
var Child = function(firstName, lastName){
    this.init.apply(this, arguments);
};
Child.inheritsFrom(Person);

我知道有点晚了,但这可能有助于某人。

尝试这样定义它,总是对我有用

function User(firstName,lastName)
{
this.firstName = ko.observable(firstName);
this.lastName = lastName;
}
function Employee(firstName,lastName)
{
    User.apply(this,arguments);
   this.firstName(firstName);
    this.lastName = lastName;
}
Employee.prototype = Object.create(User.prototype);
Employee.prototype.constructor = Employee;