I want to ask about call function behavior. I get stuck every time when I try to understand call
function.
Can anybody help me to understand what is going on by suggesting implementation of the find
method?
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)
});
Function#call
's first parameter is the this
value. To directly invoke a function, just use parentheses.
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);
});
The first param in call
will be the new this
you want to use. Then onwards are the params you want to pass.
You are basically not making a lot of use .call
here, and if you simply want to use o
you can pass null
and this.val
.
Even simpler, simply invoke the callback
function
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)
});
You're not passing call
a thisArg
argument. Well, you are, but it's value you want passed to the callback.
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)
});