| // Functions in JS are objects, so functions also have attributes and methods, including length and prototype; // Length attribute: the number of name parameters to be received by the function; Function box (name, age ){ Alert (name + age ); } Alert (box. length); // 2 s // Prototype attribute: stores all instance methods, that is, the prototype; // Prototype contains two methods: apply () and call (). Each function contains the two non-inherited methods; // The purpose of both methods is to call a function in a specific scope, which is actually equal to setting the value of this object in the function body; Var color = 'red '; Var box = { Color = 'Blue '; } Function sayColor ({ Alert (this. color ); }); SayColor (); // The scope is in window; SayColor. call (this); // The scope is in the window; SayColor. call (window); // The scope is in window; SayColor. call (box); // The scope is in the box, and the object impersonates; => red; // When the call (box) method is used, the running environment of the sayColor () method has become a box object; // The biggest benefit of using call () or apply () to expand the scope is that the object does not need to have any coupling relationship with the method; // Coupling: it means that expansion and maintenance will have a chain reaction; // That is to say, there will be no redundant Association operations between the box object and the sayColor () method, such as: box. sayColor = sayColor; Function Animal (){ This. name = "Animal "; This. showName = function (){ Alert (this. name ); } } Function Cat (){ This. name = "Cat "; } Var animal = new Animal (); Var cat = new Cat (); // Use the call or apply method to send the showName () method of the original Animal object to the cat object. // The input result is "Cat" Animal. showName. call (cat ,","); // Animal. showName. apply (cat, []); |