


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 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
];
/* Returns the internal function object that is the result of evaluating the function expression.
This internal function is the function that is executed each time it is called
- getImgInPositionedDivHtml( ... ) -
*/
return (function(url, id, width, height, top, left, altText){
/* Insert different parameters into the buffer array accordingly Position:
*/
buffAr[1] = id;
buffAr[3] = top;
buffAr[5] = left;
buffAr[13] = (buffAr[7 ] = width);
buffAr[15] = (buffAr[9] = height);
buffAr[11] = url;
buffAr[17] = altText;
/* returned by using Empty string (equivalent to concatenating array elements)
The string formed by concatenating each element of the array:
*/
return buffAr.join('');
}); / /: End of internal function expression.
})();//Self-calling
alert(getImgInPositionedDivHtml);//Display the returned function
alert(getImgInPositionedDivHtml("img.gif","img",100,50,0,0 ,"Test"));
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

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base


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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

Zend Studio 13.0.1
Powerful PHP integrated development environment

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Dreamweaver CS6
Visual web development tools