Knockout problem with prototypical inheritance

I have a problem with Knockout, where I am a prototype of a custom 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 it's hard to explain, see my violin.

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

What am I doing wrong? (or is this a knockout error?) How can I fix this problem.

+3
source share
3 answers

Since observables are functions, not properties, they are represented by one instance of the prototype of the object, in contrast to the properties that will be created on the object when they are set.

.

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

, .

+7

: 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);
+2

A bit late, I know, but it might help someone.

Try to define it like this always works 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;
+1
source

All Articles