Knockout issue with prototypical inheritance

2019-02-15 04:55发布

问题:

I have an issue with Knockout where I prototype a user object where the observable properties of my object seem to be overwritten by the last occurrence.

Therefore I cannot use the same object more than once otherwise it will be overwritten.

Although this is hard to explain, see my fiddle.

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

What am I doing wrong? (or is this a bug in Knockout?) How can I fix the problem.

回答1:

Because observables are functions and not properties they are represented by a single instance on the object prototype, unlike properties which will be created on the object when they are set.

You could use functional inheritance to achieve what you want.

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

Hope this helps.



回答2:

Here's a nice solution: http://jsfiddle.net/magikMaker/RSEcj/19/

It uses the new method inheritsFrom(), credits for this go to http://phrogz.net/js/classes/OOPinJS2.html

Combined this with the apply() method and an init() method and the magic happens... :-)

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


回答3:

Bit late i know, but this might help someone.

Try defining it like this, always works a treat for me

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;