原型继承的淘汰问题 [英] Knockout issue with prototypical inheritance

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

问题描述

我对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天全站免登陆