通常 '这个' 是指向宿主调用的方法的对象。
一个简单的例子(。您可以与function.call(的thisObject,ARG1,ARG2)或function.apply(的thisObject,[ARGLIST])覆盖此):
var myObject = {
value: 1,
report: function() {
return "value: " + this.value;
}
}
console.log(myObject.report()); // "value: 1"
应挺清楚的。
使用一个构造函数和原型,这将是:
function Reporter(v) {
this.value = v;
}
Reporter.prototype = {
report: function() { return "value: " + this.value; }
};
var myObject = new Reporter(1);
console.log(myObject.report()); // "value: 1"
作品一样。 'this'是通过调用“new Reporter(1)”创建的对象,原型中的'this'指的是调用方法“report()”的对象。 (原型来,只有发挥作用,如果没有法“的报告()”中的“myObject的”定义为自己的财产。)
现在有点多个嵌套:
function ComplexReporter(v) {
this.value = v;
}
ComplexReporter.prototype = {
report: function() { return "value: " + this.value; },
utils: {
innerReport: function() { return "value: " + this.value; }
}
};
var myObject = new ComplexReporter(1);
console.log(myObject.report()); // "value: 1"
console.log(myObject.utils.innerReport()); // "value: undefined"
第一次调用就像上面一样,并提供了预期的结果。
在第二次调用中,'this'与'myObject'不同,'myObject.prototype.utils'没有任何属性@value。 这实际上是
ComplexReporter.prototype.utils.innerReport.apply(myObject.prototype.utils, []);
因此,作为一个经验法则,“这个”是在点表示法调用对象的方法中,当最后的点之前由路径描述到最后的标识符的实体。
没有原型的最后一个例子(使它简单一点再次):
var myComplexObject = {
value: 1,
report: function() {
return "value: " + this.value;
},
utils: {
innerReport: function() {
return "value: " + this.value;
}
}
}
console.log(myComplexObject.report()); // "value: 1"
console.log(myComplexObject.utils.innerReport()); // "value: undefined"
// same as myComplexObject.utils.innerReport.apply(myComplexObject.utils, []);
console.log(myComplexObject.utils.innerReport.apply(myComplexObject, [])); // "value: 1"
而:“这个”总是被判断的那一刻,被调用的函数(这样你就可以”在构建闭包时保存'this'的上下文含义)。
我希望,这些例子了解如何“这个”工作帮助有点...
PS:如果这个对象提供了一个调用function.call()或function.apply ()是undefined或null,全局对象('self',在与'window'相同的浏览器中)被用作'this'。
它取决于 - 什么是调用回调? –
“对象”对象 – Tomatoes
请张贴一些演示此问题的实际代码。使用你的伪代码很难分辨出你有什么问题,因为语法是非标准的。 – zzzzBov