【问题标题】:knockout.js: this in child objectknockout.js:子对象中的 this
【发布时间】:2014-01-28 11:43:46
【问题描述】:

JS:

function Child() {
    this.method = function() {
         console.dir(this); // this should be 'p.child' <Child> since 
         //'method' called as a property of 'p.child'
         // but when you call it from KO it's actually 'p' <Parent>
    };
}

function Parent() {
    this.child = new Child();
}
var p = new Parent();
ko.applyBindings(p);

HTML:

 <a href="#" data-bind="click: child.method">foo</a>

是错误还是我不明白的功能?

【问题讨论】:

    标签: javascript html knockout.js


    【解决方案1】:

    您需要执行以下操作:

    function Child() {
        var self = this;
        self.method = function() {
             console.dir(self); // this should be 'p.child' <Child> since 
             //'method' called as a property of 'p.child'
             // but when you call it from KO it's actually 'p' <Parent>
        };
    }
    
    function Parent() {
        var self = this;
        self.child = new Child();
    }
    var p = new Parent();
    ko.applyBindings(p);
    

    http://jsfiddle.net/ZuHMY/1/

    请在此处查看self = this;的信息

    What underlies this JavaScript idiom: var self = this?

    更新

    这也回答了关于自我和这里的问题:

    In knockout.js, why "this" is being assigned to "self"?

    【讨论】:

    • 是的,我知道如何解决这个问题。我只是想知道这是一个错误还是我误解了一些逻辑(例如 LoD 的一些应用)?
    • 你为什么要让 self 再次成为全球性的?与。
    • @EaterOfCode 哎呀,错字。我忘了添加 var self,更新了。 :)
    • "removed var" 是否在提交消息中,我有点困惑?
    【解决方案2】:

    我不确定这一点,但敲除可能会尝试设置上下文,以便您可以从子函数和订阅中对父项进行操作。

    这个JSFiddle 展示了如何使用call(this) 更改函数调用的上下文:

    function Child() {
        this.method = function() {
             console.dir(this);
        };
    }
    
    function Parent() {
        this.child = new Child();
    } 
    var p = new Parent();
    p.child.method(); // child
    p.child.method.call(p); // parent
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-01-22
      • 2015-02-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多