Each function contains two non-inherited methods: the call() method and the apply() method. Call and apply both solve for changing the direction of this. The function is the same, but the way the parameter is passed is different. ThisObj has the properties and methods of obj. ThisObj has the properties and methods of obj. Or thisObj “inherits” obj properties and methods. The function is executed immediately after binding.
In addition to the first argument, Call can accept a list of arguments, and Apply accepts only an array of arguments.
let a = {
value: 1
}
function getValue(name, age) {
console.log(name)
console.log(age)
console.log(this.value)
}
getValue.call(a, 'yck', '24')
getValue.apply(a, ['yck', '24'])
Copy the code
Call the function, pass the arguments
Function add(x, y) {return x + y; } function myAddCall(x, y) {return add.call(this, x, y); } function myAddApply(x, y) {return add.apply(this, [x, y]); } console.log(myAddCall(10, 20)); 30 console.log(myAddApply(20, 20)); // Output 40Copy the code
Change function scope
Var name = 'c '; Var obj = {name:' 0 '}; function sayName() { return this.name; } console.log(sayName.call(this)); // Output small white console.log(sayname.call (obj)); // Enter redCopy the code
Advanced usage, implement JS inheritance
Person function Person() {this.sayName = function() {return this.name; }} // subclass Chinese function Chinese(name) {// Subclass Chinese function Chinese(name) { this.name = name; This. Ch = function() {alert(' I am Chinese '); }} // subclass America function America(name) {// use the call implementation to inherit the Person. this.name = name; This. Am = function() {alert(' I am American '); }} var Chinese = new Chinese(' Jackie '); // Call console.log(chinese.sayname ()); Var America = new America('America'); // Call console.log(America.sayname ()); / / output AmericaCopy the code
function add(c,d){ return this.a + this.b + c + d; } var s = {a:1, b:2}; The console. The log (add. Call (s, 3, 4)); // 1+2+3+4 = 10 console.log(add.apply(s,[5,6])); / / 1 + 2 + 5 + 6 = 14Copy the code
Native JS encapsulates Call
Function.prototype.myCall = function (context, ... Arg) {// const fn = Symbol(' temporary attributes ') // context[fn] = this // console.log(context,'context') // context[fn](... arg) // delete context[fn] // console.log(this(1)) this.bind(context,... Arg)()} function ma (A){console.log(A) console.log(this)} var ma1={s:99} ma.mycall (ma1,222)Copy the code