我有击倒了一个问题,我的原型用户对象在我的对象的可观察性似乎是由最后一次出现被覆盖。
因此,我不能使用相同的对象不止一次否则将被覆盖。
虽然这是很难解释的,看到我的小提琴。
http://jsfiddle.net/RSEcj/1/
我究竟做错了什么? (或者这是在淘汰赛中的错误?)我怎样才能解决这个问题。
我有击倒了一个问题,我的原型用户对象在我的对象的可观察性似乎是由最后一次出现被覆盖。
因此,我不能使用相同的对象不止一次否则将被覆盖。
虽然这是很难解释的,看到我的小提琴。
http://jsfiddle.net/RSEcj/1/
我究竟做错了什么? (或者这是在淘汰赛中的错误?)我怎样才能解决这个问题。
因为可观察量是它们是由在物体原型的单个实例所表示的功能和不性能,这不同于将在物体上时,它们被设置来创建属性。
你可以使用的功能继承来实现你想要的。
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;
};
希望这可以帮助。
这里是一个很好的解决方案: 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);
有点晚了,我知道,但是这可能帮助别人。
试着这样定义它,一种永远奏效的治疗对我来说
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;