


js apply/call/caller/callee/bind usage and difference analysis_javascript skills
Call a method of an object to replace the current object with another object (actually changing the internal pointer of the object, that is, changing the content pointed to by this of the object).
Js code
call([thisObj[,arg1[, arg2[, [,.argN]]]]])
Parameters
thisObj
Optional. The object that will be used as the current object.
arg1, arg2, , argN
Optional. A sequence of method parameters will be passed.
Description
The call method can be used to call a method instead of another object. The call method changes the object context of a function from the initial context to the new object specified by thisObj. If no thisObj parameter is provided, the Global object is used as thisObj.
Js code
Code
function Obj(){this.value="Object! ";}
var value="global variable";
function Fun1( ){alert(this.value);}
window.Fun1(); //global variable
Fun1.call(window); //global variable
Fun1.call(document.getElementById('myText ')); //input text
Fun1.call(new Obj()); //Object!
Js Code
Code
var first_object = {
num: 42
};
var second_object = {
num: 24
};
function multiply(mult) {
return this .num * mult;
}
multiply.call(first_object, 5); // returns 42 * 5
multiply.call(second_object, 5); // returns 24 * 5
2. Apply method
The first parameter of the apply method is also the object to be passed to the current object, that is, this inside the function. The following parameters are the parameters passed to the current object.
Apply and call have the same function, but there are differences in parameters. The meaning of the first parameter is the same, but for the second parameter: apply passes in a parameter array, that is, multiple parameters are combined into an array and passed in, while call is passed in as the parameter of call (from the starting with two parameters).
For example, the corresponding apply writing method of func.call(func1,var1,var2,var3) is: func.apply(func1,[var1,var2,var3]). The advantage of using apply at the same time is that you can directly add the arguments object of the current function. Passed in as the second parameter of apply.
Js code
var func=new function() {this.a="func"}
var myfunc=function(x,y){
var a="myfunc";
alert(this.a);
alert(x y);
}
myfunc.call(func,"var"," fun");// "func" "var fun"
myfunc.apply(func,["var"," fun"]) ;// "func" "var fun"
3. The caller attribute
returns a reference to the function, which is the function body that calls the current function.
functionName.caller: The functionName object is the name of the function being executed.
Note:
For functions, the caller attribute is only defined when the function is executed. If the function is called from the top level of a JScript program, then caller contains null . If the caller attribute is used in a string context, the result is the same as functionName.toString, that is, the decompiled text of the function is displayed.
Js code
function CallLevel(){
if (CallLevel.caller == null)
alert("CallLevel was called from the top level.");
else
alert("CallLevel was called by another function:n" CallLevel.caller) ;
}
function funCaller(){
CallLevel();
}
CallLevel();
funCaller()
4. callee attribute
Returns the Function object being executed, which is the body of the specified Function object.
[function.]arguments.callee: Optional function parameter is the name of the Function object currently being executed.
Note:
The initial value of the callee attribute is the Function object being executed. The
callee attribute is a member of the arguments object. It represents a reference to the function object itself. This is helpful for hiding the recursion of the
function or ensuring the encapsulation of the function. For example, the following example recursively calculates the natural numbers from 1 to n. and. And this attribute
is only available when the related function is executing. It should also be noted that callee has a length attribute, which is sometimes
used for verification. arguments.length is the actual parameter length, and arguments.callee.length is the
formal parameter length. From this, you can determine whether the formal parameter length is consistent with the actual parameter length when calling.
Js code
//callee can print itself
function calleeDemo() {
alert(arguments.callee);
}
//Used to verify parameters
function calleeLengthDemo(arg1, arg2) {
if (arguments.length ==arguments.callee.length) {
window.alert("Verify that the formal and actual parameter lengths are correct!");
return;
} else {
alert("The actual parameter length: " arguments.length);
alert("Formal parameter length: " arguments.callee.length);
}
}
//Recursive calculation
var sum = function(n){
if (n <= 0)
return 1;
else
return n +arguments.callee(n - 1)
}
5. bind
Js code
var first_object = {
num: 42
};
var second_object = {
num: 24
};
function multiply(mult) {
return this.num * mult ;
}
Function.prototype.bind = function(obj) {
var method = this,
temp = function() {
return method.apply(obj, arguments);
};
return temp;
}
var first_multiply = multiply.bind(first_object);
first_multiply(5); // returns 42 * 5
var second_multiply = multiply.bind (second_object);
second_multiply(5); // returns 24 * 5
6. JS closure (Closure)
The so-called "closure", Refers to an expression (usually a function) that has a number of variables and an environment to which these variables are bound, so that these variables are part of the expression.
Regarding closures, the simplest description is that ECMAScript allows the use of inner functions - that is, the function definition and function expression are located in the function body of another function. Furthermore, these inner functions have access to all local variables, parameters, and other inner functions declared in the outer function in which they exist. A closure is formed when one of these inner functions is called outside the outer function that contains them. That is, the inner function will be executed after the outer function returns. When this inner function is executed, it still must access the local variables, parameters and other inner functions of its outer function. The values of these local variables, parameters, and function declarations (initially) are the values when the outer function returns, but are also affected by the inner function.
In short, the function of the closure is that after the out function is executed and returned, the closure prevents Javascript's garbage collection mechanism GC from reclaiming the resources occupied by the out function, because the inner function of the out function's inner function Execution depends on the variables in the out function.
Two characteristics of closures:
1. As a reference to a function variable - it is activated when the function returns.
2. A closure is a stack area that does not release resources when a function returns.
Example 1:
Html code
< ;script type="text/javascript">
function setupSomeGlobals() {
// Local variable that ends up within closure
var num = 666;
// Store some references to functions as global variables
gAlertNumber = function() { alert(num); }
gIncreaseNumber = function() { num ; }
gSetNumber = function(x) { num = x; }
}
Example 2:
Html code
< ;script type="text/javascript">
function newClosure(someNum, someRef) {
// Local variables that end up within closure
var num = someNum;
var anArray = [1 ,2,3];
var ref = someRef;
return function(x) {
num = x;
anArray.push(num);
alert('num: ' num
' nanArray ' anArray.toString()
' nref.someVar ' ref.someVar);
}
}
var closure1 = newClosure(40, {someVar:' never-online' })
var closure2 = newClosure(99, {someVar:' BlueDestiny'})
closure1(4)
closure2(3)
Example 3:
Js code
Explanation: The key trick is to create an additional execution environment by executing an in-line function expression. Instead, use the internal function returned by the function expression as the function used in external code. At this time, the buffer array is defined as a local variable of the function expression. The function expression only needs to be executed once, and the array is created once and can be reused by functions that depend on it.
7. Prototype chain
ECMAScript defines an internal [[prototype]] attribute for the Object type. This property cannot be accessed directly through scripts, but during the parsing process of the property accessor, the object chain referenced by this internal [[prototype]] property - the prototype chain - is needed. The prototype object corresponding to the internal [[prototype]] property can be assigned or defined through a public prototype property.
Example 1:
Js code
0 0 0

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

In-depth discussion of the root causes of the difference in console.log output. This article will analyze the differences in the output results of console.log function in a piece of code and explain the reasons behind it. �...

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

Learning JavaScript is not difficult, but it is challenging. 1) Understand basic concepts such as variables, data types, functions, etc. 2) Master asynchronous programming and implement it through event loops. 3) Use DOM operations and Promise to handle asynchronous requests. 4) Avoid common mistakes and use debugging techniques. 5) Optimize performance and follow best practices.

Explore the implementation of panel drag and drop adjustment function similar to VSCode in the front-end. In front-end development, how to implement VSCode similar to VSCode...
