/* Constructor Mode */
function person (name, age, Job) {
THIS.name = name;
This.age = age;
This.job = job;
Sayname = function () {
alert (this.name);
};
}
var personthis=new person ("Thislff", "Doctor"),//① when the constructor is used
The constructor object has a constructor (constructor) property that points to the person
alert (Personthis.constructor==person);//true
/*② as a normal function call */
Person ("11", 11, "11");//Add to Windows
Windows.sayname ();//"11"
/*③ is called in the scope of another object */
var o=new Object ();
Person.call (O, "22", 22, "22");//The first parameter is O, indicating that the this keyword value in person should be given an O
O.sayname ();//"22"
the call () and apply () methods are used primarily to modify the this pointer when the function is runCall () method
The call () method is the most similar method to the Classic object impersonation method. Its first parameter is used as the object of this. Other parameters are passed directly to the function itself. For example:
function Saycolor (sprefix,ssuffix) { alert (sprefix + This.color + ssuffix);}; var obj = new Object (); obj.color = "Blue"; Saycolor.call (obj, "The color is", "a very nice color indeed.");
In this example, the function Saycolor () is defined outside the object, and even if it does not belong to any object, it can also refer to the keyword this. The color property of the object obj is equal to blue. when the call () method is called, the first parameter is obj, stating that the This keyword value in the Saycolor () function should be given to obj. the second and third arguments are strings. They match the parameters Sprefix and Ssuffix in the Saycolor () function, and the last generated message "The color is blue, a very nice color indeed." will be displayed.
Apply () method
The Apply () method has two parameters, the object used as the this and an array of arguments to pass to the function. For example:
function Saycolor (sprefix,ssuffix) { alert (sprefix + This.color + ssuffix);}; var obj = new Object (); obj.color = "Blue"; saycolor.apply (obj, New Array ("The Color is", "a very nice color indeed."));
This example is the same as the previous example, except that the Apply () method is now called. When the Apply () method is called, the first parameter is still obj, stating that the This keyword value in the Saycolor () function should be assigned to obj. The second parameter is an array of two strings, matching the parameters Sprefix and Ssuffix in the Saycolor () function, and the last generated message is still "The color is blue, a very nice color indeed." are displayed.
Introduction to the call and apply methods in JavaScript