If the function is a property of an object, then can it?
var katana = { true, function() { this. Issharp =! This . Issharp; } }; Katana.use (); Console.log (KATANA.ISSHARP); // false;
In JavaScript, inside the function, this defaults to the object that called it. In this case katana.use (), the function use is called by the object katana, so inside the function, This.issharp can manipulate katana.issharp.
The object referenced by the function through this is the context.
What does the context really mean?
function Katana () { thistruetrue, "special cases, shorthand for global variables, this can refer to properties of the Window object," ); var shuriken = { function() { thistrue ; true, "function This refers to the object that called it");
Katana () =window.katana (), this example shows clearly that the inside of the function refers to the object that called it, which is the context.
Can the context of a function be changed?
var object =function fn () { returnthis this , "Context is global object"= = Object, "Context is changed to specified object"); True
For the use of call, modify the context of the function this is the first parameter.
Different ways to change the context:
function Add (A, b) { return a + b;} console.log (Add.call (this//true Console.log (add.apply (this//true
Call and apply are often used to modify the context, they function exactly the same, there is only one difference: one receives multiple independent parameters, one receives a single array as parameters.
Exercise: Topping up the code, completing the array traversal in the callback function
function Loop (Array, fn) { forvar i = 0; i < array.length; i++ ) { // fill Full code var num = 0; loop (function(value) { = = num+ +, "Make sure the context is what we want." ); Console.log (thisinstanceof array, "context is an array instance"); });
One way to solve array traversal
function Loop (Array, fn) { forvar i = 0; i < array.length; i++ ) { fn.call (array, array[ (i], i) ; var num = 0; loop ([function(value) { = = num++, "Make sure the context is what we want." ); Console.log (thisinstanceof array, "context is an array instance"); });
JavaScript Advanced Knowledge Analysis-context