函数参数没有直接获取值
Function parameter not getting the value directly
谁能解释一下为什么函数不能以第一种方式获取对象的值?
我得到了 Backbone.View:
var some.view = Backbone.View.extend({
elements = {},
//...
//some init, filling up elements...
//...
stopTask: function() {
// Calling the function with parameters explained later
stopThisTask(...);
}
});
以及函数:
function stopThisTask(task){
console.log(task);
}
当我按以下方式调用stopThisTask
时,task
参数是undefined
stopThisTask(this.elements);
但是,当我这样做时,task
具有值
var tmp = this.elements;
stopThisTask(tmp);
谁能解释一下这是为什么?
如果我知道的话,变量是按值传递的,而对象是按引用传递的。但是,这是否意味着在某种程度上我丢失了元素对象的引用?
我怀疑 this.elements
在 stopThisTask 函数内部得到解析,因此 this
将指向 stopThisTask
而不是 stopThisTask
的调用者。
通过在调用方中显式设置 tmp
参数,您可以保证使用正确的 this
范围。
应该等同于
stopThisTask.call(this, this.elements);
谁能解释一下为什么函数不能以第一种方式获取对象的值?
我得到了 Backbone.View:
var some.view = Backbone.View.extend({
elements = {},
//...
//some init, filling up elements...
//...
stopTask: function() {
// Calling the function with parameters explained later
stopThisTask(...);
}
});
以及函数:
function stopThisTask(task){
console.log(task);
}
当我按以下方式调用stopThisTask
时,task
参数是undefined
stopThisTask(this.elements);
但是,当我这样做时,task
具有值
var tmp = this.elements;
stopThisTask(tmp);
谁能解释一下这是为什么? 如果我知道的话,变量是按值传递的,而对象是按引用传递的。但是,这是否意味着在某种程度上我丢失了元素对象的引用?
我怀疑 this.elements
在 stopThisTask 函数内部得到解析,因此 this
将指向 stopThisTask
而不是 stopThisTask
的调用者。
通过在调用方中显式设置 tmp
参数,您可以保证使用正确的 this
范围。
应该等同于
stopThisTask.call(this, this.elements);