3

我有一个关于 Knockout 的问题,我在其中创建了一个用户对象的原型,其中我的对象的可观察属性似乎被最后一次出现覆盖了。

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

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

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

我究竟做错了什么?(或者这是 Knockout 中的错误?)我该如何解决这个问题。

4

3 回答 3

7

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

您可以使用功能继承来实现您想要的。

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;
};

希望这可以帮助。

于 2012-05-09T17:00:02.813 回答
2

这是一个很好的解决方案: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);
于 2012-05-09T21:00:52.630 回答
1

我知道有点晚了,但这可能会对某人有所帮助。

尝试像这样定义它,对我来说总是一种享受

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;
于 2015-01-17T21:09:39.197 回答