For the written questions of bind and call, why are the results performed with call and without call the same?
the interview questions are as follows:
var s = {
s: "student",
getS:function(){
console.log(this.s);
}
};
var t = {
s: "teacher chen"
}
var getS = s.getS;
var getS1 = getS.bind(s);
the correct result is:
getS1(); // student
getS1.call(t); //student
The sentence
var getS1 = getS.bind (s) means to create a new function and bind the this of the new function to the object s through bind,. Output student, yes. But didn"t getS1.call (t), bind this to the object t through the call method? Why is the output still student instead of teacher chen?
is very interested in this problem. After looking up some materials
, the following is the Polyfill of bind in MDN. You can see that the function returned by bind will change this, only when it uses the new method as the constructor call. In other cases, the this has been bound
.
if (!Function.prototype.bind) {
Function.prototype.bind = function(oThis) {
if (typeof this !== 'function') {
// closest thing possible to the ECMAScript 5
// internal IsCallable function
throw new TypeError('Function.prototype.bind - what is trying to be bound is not callable');
}
var aArgs = Array.prototype.slice.call(arguments, 1),
fToBind = this,
fNOP = function() {},
fBound = function() {
// this instanceof fNOP === true,fBoundnew
return fToBind.apply(this instanceof fNOP
? this
: oThis,
// (fBound).bind
aArgs.concat(Array.prototype.slice.call(arguments)));
};
//
if (this.prototype) {
// Function.prototype doesn't have a prototype property
fNOP.prototype = this.prototype;
}
// fBound.prototypefNOP,
// fBoundnew,newthisfBound,__proto__fNOP
fBound.prototype = new fNOP();
return fBound;
};
}
in addition, the author https://blog.csdn.net/learnin. has done some experiments. The conclusion is: for which function to use the bind () method is to change the value of the function, and to set its parameters, or to understand it like Kriging, to preset the parameters first
.
I'll tell you about
new
upstairs. I'll write you a similar simple example and you'll know
.
function fn(){
console.log(this)
}
var test = function(){
//this
return fn.call('123')
}
test();//123
test.call('aaa');//123
because the binding level of bind is higher than that of call/apply.
review the usage of this on MDN. It says bind:
"calling f.bind (someObject) creates a function with the same function body and scope as f, but in this new function, this will be permanently bound to the first parameter of bind, no matter how the function is called."
compared to the example I gave, the function body and scope of var getS1 = getS.bind (s); getS1 and getS are the same, but the this of getS1 is permanently bound to object s, and the value of this cannot be changed even with the call method.