Call the function
Function.prototype.call()
The title | content |
---|---|
The definition of the Call | What is the Call function? |
The use of the Call | How to use the Call function? |
Call implementation principle | How do I implement the Call function? |
The Call of the sample | The Call function implements inheritance, etc |
The definition of the Call
call()
Method uses aThe specifiedthis
valueandOne given separatelyorMultiple parameterstoCall a function.
function People(name, age) {
this.name = name;
this.age = age;
}
function Person(name, age) {
People.call(this, name, age);
this.tall = '185';
}
var person = new Person('jackdan'.25);
console.log(person) // Object { name: "jackdan", age: 25, tall: "185" }
console.log(person.name) // "jackdan"
Copy the code
The call of the grammar
/ * * *@desciption Function.prototype.call()
*
*/
function.call(thisArg, arg1, arg2, arg3, ...)
Copy the code
Parameters that
-
ThisArg: Optional. The this value used when function is run. Note that this may not be the actual value seen by this method: if the function is in non-strict mode, specifying null or undefined is automatically replaced with pointing to a global variable, and the original value is wrapped.
-
In strict ECMAScript 5 mode, the first argument to call() and apply(), thisArg, becomes this, even if the argument passed in is original or even null or undefined. In ECMAScript 3 and non-strict mode, null and undefined are replaced by global objects, while other raw values are replaced by corresponding Wrapper objects.
// Non-strict mode
var name = 'jackdan';
function sayName() {
console.log(this); // Window
console.log('My Name is %s'.this.name)
}
sayName.call();
Copy the code
- Strict mode:
// Strict mode
'use strict'
var name = 'jackdan';
function sayName() {
console.log(this); // undefined
console.log('My Name is %s'.this.name); // Uncaught TypeError: Cannot read property 'name' of undefined
}
sayName.call();
Copy the code
arg1, arg2, agr3, ...
: Specifies the parameter list.
The return value
- Using the callerTo provide the
this
Values andParameter Is the return value of the call to the function. Returns if the method does not return a valueundefined
.
describe
call()
To allow forDifferent object allocationandcallBelonging to an objectFunction/method.call()
Provides a new this value for the currently called function/method. You can usecall
To implement inheritance: write one method and let anotherThe new object inherits it(Instead of writing the method again in a new object)
function People(name, age) {
this.name = name;
this.age = age;
}
function PersonJack(name, age) {
People.call(this, name, age);
this.tall = 185
}
function PersonRose(name, age) {
People.call(this, name, age);
this.tall = 165;
}
var jackdan = new PersonJack('jackdan'.26);
var rose = new PersonRose('rose'.24);
console.log(jackdan); // PersonJack {name: "jackdan", age: 26, tall: 185}
console.log(rose); // PersonRose {name: "rose", age: 24, tall: 165}
Copy the code
The realization of the Call
call()
Method is using a specifiedthis
Values and several specified parameter values are called by a function or method.
var personObj = {
name: 'jackdan'
}
var sayName = function() {
console.log(this.name)
}
sayName.call(personObj); // jackdan
Copy the code
- Is equivalent to
var personObj = {
name: 'jackdan'.sayName: function() {
console.log(this.name);
}
}
personObj.sayName(); // jackdan
// 1. Set the function to an object property
// 2. Execute this function
// 3. Delete the function
personObj.fn = personObj.sayName;
personObj.fn(); // jackdan
delete personObj.fn(); // jackdan
Copy the code
Function.prototype.myCall
implementation
Function.prototype.myCall = function(context) {
context.fn = this;
context.fn();
delete context.fn();
}
var personObj = {
name: 'jackdan'
}
var sayName = function() {
console.log(this.name);
}
sayName.myCall(personObj);
Copy the code
Function.prototype.myCall
Implementation with parameters
var personObj = {
tall: 185
}
var sayName = function(name, age) {
console.log(name);
console.log(age);
console.log(this.tall);
}
sayName.call(personObj, 'jackdan'.26); // jackdan 26 185
Copy the code
Function.prototype.myCall = function(context) {
context = Object(context) || window;
context.fn = this;
var args = [];
for(var i = 0, len = arguments.length; i < len; i++) {
args.push('arguments[' + i + '] ');
}
var result = eval('context.fn(' + args + ') ');
delete context.fn;
return result;
}
var personObj = {
tall: 185
}
var sayName = function(name, age) {
console.log(name);
console.log(age);
console.log(this.tall);
}
sayName.myCall(personObj, 'jackdan'.26);
Copy the code
The sample
Call the parent constructor using the call method
- In a child constructor, you can callParent constructorthe
call
Methods toImplementation inheritance, similar to theJava
Is written in. In the following example, useFood
andToy
The constructorAll object instances created are owned in theProduct
Constructorname
Properties andprice
Property, butcategory
Attributes are inRespective constructorsIs defined in.
function Product(name, price) {
this.name = name;
this.price = price;
}
function Food(name, price) {
Product.call(this, name, price);
this.category = 'food';
}
function Toy(name, price) {
Product.call(this, name, price);
this.category = 'toy';
}
var cheese = new Food('feta'.5);
var fun = new Toy('robot'.40);
console.log(cheese); // Food {name: "feta", price: 5, category: "food"}
console.log(fun); // Toy {name: "robot", price: 40, category: "toy"}
Copy the code
Call anonymous functions using the call method
- In the next example
for
In the circulator, we created oneAnonymous functionsAnd then by calling the functioncall
Method that treats each array element as the specifiedthis
Value executes that anonymous function. The main purpose of this anonymous function is to add one to each array element objectsayName
Method, this onesayName
The printout () method prints each element in an arrayCorrect index number. Of course, you don’t have to have the array element act asthis
The value is passed to the anonymous function (normal arguments will do) for demonstration purposescall
The use of.
var people = [
{ name: 'jackdan'.age: 26 },
{ name: 'rose'.age: 24}];for (var i = 0; i < people.length; i++) {
(function(i) {
this.sayName = function() {
console.log(The '#' + i + ' ' + this.name + ':' + this.age);
}
this.sayName();
}).call(people[i], i);
}
// #0 jackdan: 26
// #1 rose: 24
Copy the code
Call the function using the call method and specify ‘this’ for the context
- In the example below, when called
sayName
Method of the time of the methodthis
The value is bound toobj
Object.
function sayName() {
var reply = [this.person, 'typically sleep between'.this.sleepDuration].join(' ');
console.log(reply);
}
var obj = {
person: 'jackdan'.sleepDuration: '8 and 10 hours'
};
sayName.call(obj); // jackdan typically sleep between 8 and 10 hours
Copy the code
Call a function using the call method without specifying the first argument (argument)
- In the example below, we call
sayName
Method, but does not pass itThe first parameter. If there is noPass the first argument.this
Will be bound toGlobal object.
// Non-strict mode
var name = 'jackdan';
function sayName() {
console.log(this); // Window
console.log('My Name is %s'.this.name)
}
sayName.call();
Copy the code
- Strict mode: If the first argument is not passed,
this
The value of will be undefined. - Suggestion: You still need to write programs in strict mode to avoid the contamination of scope by global objects.
// Strict mode
'use strict'
var name = 'jackdan';
function sayName() {
console.log(this); // undefined
console.log('My Name is %s'.this.name); // Uncaught TypeError: Cannot read property 'name' of undefined
}
sayName.call();
Copy the code
Developer.mozilla.org/zh-CN/docs/…