gpt4 book ai didi

javascript - 使用KnockoutJS和简单类继承时丢失对self的引用

转载 作者:行者123 更新时间:2023-11-28 20:53:21 24 4
gpt4 key购买 nike

我正在使用John Resig's "Simple JavaScript Inheritance"创建可以继承的类。我还使用KnockoutJS来计算可观察值。问题在于试图将这两个概念结合起来。当我尝试在计算的可观察对象中获得对self的引用时,我得到的是“ Window”对象,而不是预期的实际对象。这是一个快速的代码示例:

window.mynamespace.myclass = Class.extend({
init: function() {

},
someProperty: ko.observable(10),
someComputedProperty: ko.computed(function() {
return this.someProperty();
}, this)
});


不幸的是,找不到this.someProperty(),因为“ this”是对Window的引用。有什么想法或想法吗?

最佳答案

您始终可以将它们添加到init中。在knockout's own examples中,它们在构造函数中进行绑定。

window.mynamespace.myclass = Class.extend({
init: function() {
this.someProperty = ko.observable(10);
this.someComputedProperty = ko.computed(function() {
return this.someProperty();
}, this);
}
});


或捕获对 this的引用而忘记绑定:

window.mynamespace.myclass = Class.extend({
init: function() {
var self = this;
self.someProperty = ko.observable(10);
self.someComputedProperty = ko.computed(function() {
return self.someProperty();
});
}
});




编辑:

为了演示如何扩展课程:

window.mynamespace.myotherclass = window.mynamespace.myclass.extend({
init: function() {
// do anything myotherclass init, like another observable
this.someOtherProperty = ko.observable(10);

// incidentally you *can* have private variables with this pattern
var imPrivate = 1;
this.getImPrivate = function() {
return imPrivate;
};

// then call super (maybe with arguments, maybe just passing them)
this._super('foobar');
}
});

关于javascript - 使用KnockoutJS和简单类继承时丢失对self的引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12041269/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com