最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Knockout issue with prototypical inheritance - Stack Overflow

programmeradmin1浏览0评论

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.

/

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

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/RSEcj/1/

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

Share Improve this question asked May 9, 2012 at 16:39 Rene PotRene Pot 24.8k7 gold badges70 silver badges92 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 7

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/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.

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

It uses the new method inheritsFrom(), credits for this go to http://phrogz/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);

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;
发布评论

评论列表(0)

  1. 暂无评论