JavaScript简单调用函数的行为



我想问一下调用函数的行为。每次当我试图理解call函数时,我都被卡住了。

谁能通过建议实施find方法来帮助我理解发生了什么?


Hoge = function (val) {
this.val = val;
//console.log("this.val" + this.val);
};
Hoge.prototype.find = function (callback) {
callback.call(this.val);
};
var h = new Hoge(1);
h.find((o) => { 
console.log(o);  // expected 1 but undefined
console.log(o === 1); // expected true but  its false (caz o is undefined)
});

您没有向call传递thisArg参数。你的,但它的值是你想传递给回调的

Hoge = function(val) {
this.val = val;
//console.log("this.val" + this.val);
};
Hoge.prototype.find = function(callback) {
// callback.call(this.val);
callback.call(this, this.val); // call wants a "this" argument
// callback(this.val); // Could just do this instead
};
var h = new Hoge(1);
h.find((o) => {
console.log(o); // expected 1 but undefined
console.log(o === 1); // expected true but  its false (caz o is undefined)
});

Function#call的第一个参数是this的值。要直接调用函数,只需使用括号。

callback(this.val);

Hoge = function (val) {
this.val = val;
};
Hoge.prototype.find = function (callback) {
callback(this.val);
};
var h = new Hoge(1);
h.find((o) => { 
console.log(o);
console.log(o === 1);
});

call中的第一个参数将是您想要使用的新this。然后是你想要传递的参数。

你基本上不会在这里大量使用.call,如果你只是想使用o,你可以传递nullthis.val

更简单,只需调用callback函数

Hoge = function (val) {
this.val = val;
//console.log("this.val" + this.val);
};
Hoge.prototype.find = function (callback) {
//Both work
callback.call(null,this.val);
callback(this.val);
};
var h = new Hoge(1);
h.find((o) => { 
console.log(o);  // expected 1 but undefined
console.log(o === 1); // expected true but  its false (caz o is undefined)
});

最新更新