当前位置:网站首页>JS call and apply
JS call and apply
2022-07-27 09:09:00 【The gentle wind is attributed to you with a smile】
a.call and apply Methods,
call Method :
grammar :call([thisObj[,arg1[, arg2[, [,.argN]]]]])
Definition : A method that calls an object , Replace the current object with another object .
explain : call Method can be used to call a method instead of another object .call Method to change the object context of a function from its initial context to thisObj New object specified . If not provided thisObj Parameters , that Global Object is used as thisObj.
apply Method :
grammar :apply([thisObj[,argArray]])
Definition : A method of applying an object , Replace the current object with another object .
explain : If argArray Is not a Valid array Or not arguments object , Then it will lead to a TypeError. If not provided argArray and thisObj Any parameter , that Global Object will be used as thisObj, And no arguments can be passed .
Case study :
function add(a,b){ alert(a+b);}
function sub(a,b){ alert(a-b);}
add.call(sub,3,1);The result is 4. call add function , But the calling object ( Context ) No add object , It is sub Function object . Be careful :js The functions in are actually objects , The function name is right Function References to objects .


function Animal(){
this.name = "Animal";
this.showName = function(){ alert(this.name);}
}
function Cat(){ this.name = "Cat"; }
var animal = new Animal();
var cat = new Cat();
animal.showName.call(cat,",");// The output is "Cat"
animal.showName.apply(cat,[]);// The output is "Cat"

call It means to put animal The way to do this is to put cat On the implementation , The context is cat, original cat It's not showName() Method , Now it's a animal Of showName() How to put it in cat Up and down , and cat Of this.name yes Cat. therefore this.name Should be Cat
Implementation inheritance


function Animal(name){
this.name = name;
this.showName = function(){ alert(this.name);}
}
function Cat(name){ Animal.call(this, name); }
var cat = new Cat("Black Cat");
cat.showName();

Animal.call(this) It means to call Animal Method , But use this Object instead of Animal object , The context becomes this.new Cat("Black Cat") Use in Animal.call Set properties for the current context name And methods showName.
expand : multiple inheritance


function Class10(){
this.showSub = function(a,b){ alert(a-b); }
}
function Class11(){
this.showAdd = function(a,b){ alert(a+b); }
}
function Class2(){
Class10.call(this);
Class11.call(this);
}

remarks :js There are other ways to inherit , For example, use prototype chain , This does not belong to the scope of this article , only Is here to explain call Usage of . Said the call , Of course, apply, These two methods basically mean the same thing , The difference lies in call The second parameter of can be of any type , and apply The second argument to must be an array or arguments.
b.arguments Use
What is? arguments
arguments Yes JavaScript A built-in object in , It's weird , And it's often overlooked , But it's really important . All the major js Function libraries all use arguments object . therefore agruments Object to javascript Programmers must be familiar with .
All functions have their own arguments object , It includes the parameters that the function calls . He is not an array , If you use typeof arguments, The return is ’object’. Although we can use the method of calling data to call arguments. such as length, also index Method . But count Of the group push and pop Object is not applicable .
Use arguments Create a flexible function
Looks like argument Objects are very limited to use , But it's actually a very useful object . You can use argument Object allows functions to be called in an indefinite number Parameters of . stay Dean Edwards Of base2 There is a formatted function in the library , Demonstrates this flexibility .


function format(string) {
var args = arguments;
var pattern = new RegExp('%([1-' + arguments.length + '])', 'g');
return String(string).replace(pattern, function(match, index,position,all) {
console.log(match + '&' + index + '&' + position + '&' + all);
return args[index];
});
};

Drop out format('And the %1 want to know whose %2 you %3', 'papers', 'shirt', 'wear'); The result is "And the papers want to know whose shirt you wear"; Console print as
%1&1&8&And the %1 want to know whose %2 you %3
%2&2&30&And the %1 want to know whose %2 you %3
%3&3&37&And the %1 want to know whose %2 you %3
hold arguments Object into a real array
although arguments Object is not a real javascript Array , But we can easily convert it into standard data , Then perform array operation .
var args = Array.prototype.slice.call(arguments);
So now this variable args It contains a standard that contains all the parameters of the function javascript Array objects .
expand : Use the... In the previous section format function , Through preset arguments Object creation function


function makeFunc() {
var args = Array.prototype.slice.call(arguments);
var func = args.shift();
return function() {
return func.apply(null, args.concat(Array.prototype.slice.call(arguments)));
};
}

This method will take out the first parameter , And then return a curry The transformation function , The curry The parameters of the function ( the second arguments) Will and makeFunc The parameters starting from the second parameter are combined into a new array . And back to makeFunc Of the first parameter apply call
perform
var majorTom = makeFunc(format, "This is Major Tom to ground control. I’m %1.");
majorTom("stepping through the door");The result is :"This is Major Tom to ground control. I’m stepping through the door."
Console printing :%1&1&41&This is Major Tom to ground control. I’m %1.
[function.]arguments.callee
explain :arguments.callee Method returns the function itself being executed .
callee The attribute is arguments A member of the object , It represents a reference to the function object itself , This is conducive to the recursion of anonymous functions or ensure the encapsulation of functions , For example, recursive computation in the following example 1 To n The sum of the natural numbers of . This property is only available when the related function is executing . What's more, we need to pay attention to callee Have length attribute , This property is sometimes better used for validation .arguments.length Is the argument length ,arguments.callee.length It's a parameter ( The required parameters specified in the definition ) length , From this, we can judge whether the length of formal parameter is consistent with that of actual parameter when calling .


// Used to validate parameters
function calleeLengthDemo(arg1, arg2) {
if (arguments.length==arguments.callee.length) {
window.alert(" Verify that the formal and argument lengths are correct !");
return;
} else {
alert(" Argument length :" +arguments.length);
alert(" Parameter length : " +arguments.callee.length);
}
}
// Recursive computation
var sum = function(n){
if (n <= 0) return 1;
else return n +arguments.callee(n - 1)
}
// More general recursive function :
var sum = function(n){
if (1==n) return 1;
else return n + sum (n-1);
}

Invocation time :alert(sum(100)); The function contains a pair of sum The quotation of oneself , The function name is just a variable name , Call... Inside the function sum It is equivalent to calling a global variable , Can not be well reflected in the call itself , Use this time callee Would be a better way .
expand functionName.caller
explain : Returns who called functionName function .functionName Object is the name of the function being executed . For functions ,caller Attributes are defined only when the function is executed . If the function is called from the top level , that caller It includes null . If used in a string context caller attribute , So the result and functionName.toString equally , in other words , The decompiled text of the function is displayed . The following example illustrates caller Property usage :


// caller demo {
function callerDemo() {
if (callerDemo.caller) {
var a= callerDemo.caller.toString();
alert(a);
} else {
alert("this is a top function");
}
}
function handleCaller() {
callerDemo();
}
handleCaller();

Execution results :

c.undefined and null
Most computer languages , There is only one representation " nothing " Value , such as ,C Linguistic NULL,Java Linguistic null,Python Linguistic none,Ruby Linguistic nil. It's a little strange that ,JavaScript Language has two expressions " nothing " Value :undefined and null. Why is that ?
similarity
stay JavaScript in , Assign a variable to undefined or null, honestly , Almost no difference .
The code is as follows :
var a = undefined; var a = null;
In the above code ,a The variables are assigned to undefined and null, These two expressions are almost equivalent .
undefined and null stay if In the sentence , Will be automatically converted to false, The equality operator even directly reports that they are equal .


if (!undefined)
console.log('undefined is false');
// undefined is false
if (!null)
console.log('null is false');
// null is false
undefined == null
// true

The above code shows , How similar their behavior is ! But let's check undefined and null But found that the types are different .js There is no... In the base type null type
typeof null;//"object" typeof undefined;//"undefined"
Both however undefined and null The meaning and usage of , Why set two such values at the same time , This is not an unprovoked increase JavaScript Complexity , It bothers beginners Do you ?Google company-developed JavaScript A substitute for language Dart Language , It clearly stipulates that only null, No, undefined!
Historical reasons
original , This is related to JavaScript The history of .1995 year JavaScript When it was born , Initial image Java equally , Only set null As an expression of " nothing " Value .
according to C The tradition of language ,null Designed to automatically turn into 0.
Number(null) // 0 5 + null // 5
however ,JavaScript Designer Brendan Eich, I don't think it's enough , There are two reasons .
First ,null Like in Java Same as in , Being treated as an object .
typeof null // "object"
however ,JavaScript The data types of are divided into original types (primitive) And composite types (complex) Two categories: ,Brendan Eich I think it means " nothing " Better not be an object .
secondly ,JavaScript The original version of did not include an error handling mechanism , When a data type mismatch occurs , It is often automatic type conversion or silent failure .Brendan Eich Think , If null Automatically turn to 0, It's not easy to find mistakes . therefore ,Brendan Eich Another one was designed undefined.
Original design
JavaScript The original version of is distinguished in this way :null Is a representation of " nothing " The object of , When it is converted to a number, it is 0;undefined Is a representation of " nothing " Original value , When it is converted to a number, it is NaN.
Number(undefined) // NaN 5 + undefined // NaN
Current usage
however , The above distinction , It soon proved infeasible in practice . at present ,null and undefined It's basically synonymous , There are only a few subtle differences .
null Express " There is no object ", That is, there should be no value . Typical usage is :
(1) As an argument to a function , The parameter representing the function is not an object .
(2) As the end of the object prototype chain .
Object.getPrototypeOf(Object.prototype) // null
undefined Express " Lack of value ", This is where there should be a value , But there is no definition . Typical usage is :
(1) Variables are declared , But when there is no assignment , Is equal to undefined.
(2) When you call a function , The parameter that should be provided is not provided , This parameter is equal to undefined.
(3) Object has no assigned property , The value of this property is undefined.
(4) When the function does not return a value , Default return undefined.


var i;
i // undefined
function f(x){console.log(x)}
f() // undefined
var o = new Object();
o.p // undefined
var x = f();
x // undefined

边栏推荐
- Low cost, low threshold, easy deployment, a new choice for the digital transformation of 48 million + small and medium-sized enterprises
- Interface test tool -postman usage details
- [acl2020] a novel method of component syntax tree serialization
- ArkUI中的显式动画
- PVT's spatial reduction attention (SRA)
- [flutter -- geTx] preparation
- Software testing function testing a full set of common interview questions [function testing - zero foundation] essential 4-1
- Size limit display of pictures
- 对 int 变量赋值的操作是原子的吗?
- 8 kinds of visual transformer finishing (Part 1)
猜你喜欢

PyQt5快速开发与实战 4.1 QMainWindow

MySQL transaction

Deep understanding of Kalman filter (1): background knowledge

CUDA programming-01: build CUDA Programming Environment

The wechat installation package has soared from 0.5m to 260m. Why are our programs getting bigger and bigger?

CUDA programming-04: CUDA memory model

ctfshow 终极考核

Mangodb simple to use

"Weilai Cup" 2022 Niuke summer multi school training camp 1
![[acl2020] a novel method of component syntax tree serialization](/img/24/b8ec489966f7b1deef82b2eefa4d1b.png)
[acl2020] a novel method of component syntax tree serialization
随机推荐
C# 窗体应用常用基础控件讲解(适合萌新)
二叉树讲解
tensorflow包tf.keras模块构建和训练深度学习模型
四个开源的人脸识别项目分享
[flutter -- geTx] preparation
Tensorflow package tf.keras module construction and training deep learning model
pollFirst(),pollLast(),peekFirst(),peekLast()
CUDA Programming -03: thread level
Matlab uses m file to produce fuzzy controller
如何注册码云账号
Intel, squeezed by Samsung and TSMC, finally put down its body to customize chip technology for Chinese chips
D3.v3.js data visualization -- pictures and tips of force oriented diagram
【微服务~Sentinel】Sentinel之dashboard控制面板
QDoubleValidator不生效问题解决办法
Understand various IOU loss functions in target detection
BOM的常用操作和有关获取页面/窗口高度、宽度及滚动的兼容性写法
Primary function t1744963 character writing
PVT's spatial reduction attention (SRA)
存储和计算引擎
基于restful页面数据交互