原型继承的敲除问题 [英] Knockout issue with prototypical inheritance

查看:23
本文介绍了原型继承的敲除问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用 Knockout 时遇到了一个问题,其中我对用户对象进行了原型设计,而我的对象的可观察属性似乎被上次出现的对象覆盖了.

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/

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

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

推荐答案

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

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

希望这会有所帮助.

这篇关于原型继承的敲除问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆