繁体   English   中英

基因敲除.js:在子对象中

[英]knockout.js: this in child object

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>

是错误还是我不了解的功能?

您需要执行以下操作:

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;的信息self = this;

JavaScript惯用语的基础是什么:var self = this?

更新

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

在淘汰表.js中,为什么将“ this”分配给“ self”?

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM