Home > Article > Web Front-end > What is the context of a JavaScript function?
Function context
In languages such as Java or C/C++, methods (functions) can only exist attached to objects and are not independent. In JavaScript, a function is also an object and is not part of any other object. It is particularly important to understand this, especially for understanding functional JavaScript. In functional programming languages, functions are considered first-class.
The context of a function can change, therefore, this within the function can also change. The function can be used as a method of one object or as a method of another object at the same time. In short, the function itself is independent . The context of the function can be modified through the call or apply function on the Function object:
call and apply
call and apply are usually used to modify the context of the function, the this pointer in the function will be replaced by the first parameter of call or apply. Let’s take a look at the examples in JavaScript Getting Started with Objects and JSON:
//定义一个人,名字为jack var jack = { name : "jack", age : 26 } //定义另一个人,名字为abruzzi var abruzzi = { name : "abruzzi", age : 26 } //定义一个全局的函数对象 function printName(){ return this.name; } //设置printName的上下文为jack, 此时的this为jack print(printName.call(jack)); //设置printName的上下文为abruzzi,此时的this为abruzzi print(printName.call(abruzzi)); print(printName.apply(jack)); print(printName.apply(abruzzi)); 只有一个参数的时候call和apply的使用方式是一样的,如果有多个参数: setName.apply(jack, ["Jack Sept."]); print(printName.apply(jack)); setName.call(abruzzi, "John Abruzzi"); print(printName.call(abruzzi));
The result obtained is:
Jack Sept. John Abruzzi apply的第二个参数为一个函数需要的参数组成的一个数组,而call则需要跟若干个参数,参数之间以逗号(,)隔开即可。
The above is the detailed content of What is the context of a JavaScript function?. For more information, please follow other related articles on the PHP Chinese website!