How to use 'this' in nested object?
This question already has an answer here:
If not works this way. The self
technic is a closure and it should be defined in the same function as being used. For example:
function myFunc() {
var self = this;
anotherFuncWithCallback( function() { self.myValue = this.valueFromOtherContext; });
}
You can't bind this
to your method the way you want. If you have bind problems, you need to change your method call:
myObject.myMethod.bind(myObject)("parameters");
It will bind the right object to this
before calling your method.
By the way, you can change your class defintion to this:
var LayoutConstructor = function() {
var self = this;
this.newsroom = {
buildSidebar: function() {
//some code...
//get the error: Cannot read property 'buildBoxWrapper' of undefined
self.general.buildBoxWrapper($(".sidebar .box-wrapper"));
}
};
this.buildNewsroom = function() {
this.newsroom.buildSidebar();
};
this.general = {
// Build the box-wrapper
buildBoxWrapper: function(boxWrapper) {
//some code...
}
}
}
链接地址: http://www.djcxy.com/p/94902.html
上一篇: 'this'在这种情况下如何工作?
下一篇: 如何在嵌套对象中使用'this'?