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

标签 javascript inheritance knockout.js

我正在使用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/

相关文章:

knockout.js - Knockout JS - 使用静态类名和数据绑定(bind)类名

javascript - 为什么不将用户输入放入空数组?

javascript - 替换特定的标签名称javascript

Javascript:有没有办法清除用户输入的历史记录?

r - 为什么 S4 继承在环境之间丢失?

c# - 使用 protobuf-net 序列化继承的类

javascript - knockout js变量设置类似于调用函数

javascript - 手机间隙 : Angular Controller does not work in new window

c++ - 使用内部类型作为模板参数继承模板类

javascript - knockout : Change css class based on value of observable