1. call
Effect: Changes this point to call the function to pass in an argument.
Grammar:
Effect: Changes this point to call the function to pass in an argument.
Grammar:
function.call(this, arg1, arg2, ...)
Application: The child constructor inherits the properties of the parent constructor
function Father (surname) {
this.surname = surname;
}
function Son (surname) {
// Changes this in the parent constructor to this in the child constructor, and passes a value to this attribute.
Father.call(this, surname);
}
var xiaoming = new Son('xiao');
2. apply
Effect: Changes this point to call the function to pass in an argument.
Grammar:
function.apply(this, [arg1, arg2, ...])
Application: Call a method in Math
var arr = [1, 2, 3];
Math.max.apply(Math, arr);
3. bind
Effect: Change this point to pass in parameter.
Grammar:
function.bind(this, arg1, arg2, ...)
Application: Change the this pointer in setTimeout
var obj = {
data: 'first',
init: function () {
setTimeout(function(){
this.data = 'last';
}.bind(this), 3000)
}
}
obj.init();