1. The Bind function
Returns a copy of the original function with the specified this value and initial arguments.
1.1 Understanding and use of Bind function
1.1.1 The first is the use of Bind
// Create a global variable
friends = ['glo_zhao'.'glo_dong'.'glo_sun']
const changInfo = {
name: 'chang'.friends: ['zhao'.'qian'.'sun'.'li'].getOneFri: function () {
// Returns a random bit of a friend
const index = Math.floor(Math.random() * this.friends.length)
return this.friends.slice(index, index + 1)}}// Test the function
console.log(changInfo.getOneFri());
// Return a random value of chang.friends, currently this points to changInfo
// Create a function
const getRanFri = changInfo.getOneFri;
console.log(getRanFri());
// Returns the value of the random global variable window.friends. The current this executes window
// Create a new role
const newPerson = {
friends: ['per_liu'.'per_wang']}// Create a binding function
const bindGetRanFir = getRanFri.bind(newPerson)
console.log(bindGetRanFir());
// Return a random friend of newPerson
Copy the code
1.1.2 Constructor binding
function Point(x, y) {
this.x = x
this.y = y
}
Point.prototype.toString = function () {
return ` (The ${this.x} , The ${this.y}) `
}
const test = new Point(1.2)
console.log(test.toString()); // (1 , 2)
const getPoint = Point.bind(null.3.4)
const exp = new getPoint()
console.log(exp.toString()); // (3 , 4)
Copy the code
1.2 Implementation principle of Bind function
if (!Function.prototype.myBind) {
(function () { // Execute the function immediately
// const arrayPrototypeSlice = Array.prototype.slice;
Function.prototype.myBind = function (otherThis) {
if (typeof this! = ='function') { // Check if it is a function call
throw new TypeError('Function.prototype.myBind - what is trying to be bound is not callable')}const _this = this
const args = [...arguments].slice(1)
return function F() {
if (this instanceof F) { // Check if it is a constructor binding
return new_this(... args, ... arguments) }return_this.apply(otherThis, args.concat(... arguments)) } } })() }Copy the code
2. Call the function
The call() method calls a function with a specified this value and one or more arguments given separately.
2.1 Understanding and application of Call Function
2.1.1 Direct call of functions
const messsage = 'Hello world'
const point = () = > {
// Through the scope chain, this points to the window and message points to the global scope
console.log('message is ', messsage);
}
point.call() // message is Hello world
Copy the code
2.1.2 Use call to modify the this pointer
const obj = {
messsage: 'obj_message'
}
const point = function () {
// Through the scope chain, this points to the window and message points to the global scope
console.log('message is '.this.messsage);
}
point.call(obj) // message is obj_message
Copy the code
2.1.3 Call the parent constructor through the call function to achieve function inheritance
function Father(firstName, lastName) { // Define a father constructor
this.lastName = lastName
this.firstName = firstName
this.getFamilyName = function () {
return `The ${this.lastName} The ${this.firstName}`}}function Child(firstName, father) { // Define a child constructor
Father.call(this, firstName, father.lastName)
this.firstName = firstName // Redirect the name
}
let zhang_Fa = new Father('san'.'zhang')
let zhang_ch = new Child('liang', zhang_Fa)
console.log(zhang_ch.getFamilyName()); // zhang liang
Copy the code
2.2 Implementation of call function
if (!Function.prototype.myCall) {
(function () {
Function.prototype.myCall = function (context) {
context = context || window // Get the function variable
context.fn = this // Get the caller function
/ / point. MyCall (obj, arg1, arg2,...) = > args = [arg1...] / / access parameters
const args = [...arguments].slice(1)
/ / point. MyCall (obj, arg1, arg2,...) = > obj. Fn (arg1, arg2,...) / / carry the return value of parameters is carried out
constresult = context.fn(... args)delete context.fn // Delete the bound function
return result
}
})()
}
Copy the code
3. Apply the function
The apply() method calls a function with a given this value and arguments in the form of an array (or array-like object).
3.1 Implementation of Apply
The use of apply() is similar to the use of call(), except that the parameters of the function apply are arrays and call is a list of parameters
if (!Function.prototype.myApply) {
(function () {
Function.prototype.myApply = function (context) {
context = context || window
context.fn = this // Function binding
let result
if (arguments[1]) { // If there is a second argumentresult = context.fn(... arguments[1])}else {
result = context.fn()
}
delete context.fn
return result
// const args = [...argumentsr].slice(1)}}}) ()Copy the code