1. method definition
Call method: Syntax: call ([thisObj, arg1, arg2, arg ...... N]), the parameter arg can only be in the form of a list, such as: a, B, c Definition: Call one method of an object and replace the current object with another object. Note: The call method can be used to call a method instead of another object. The call method can change the object context of a function from the initial context to the new object specified by thisObj. If the thisObj parameter is not provided, the Global object is used as thisObj. Apply method: Syntax: apply ([thisObj, [argArray, arguments]). The parameter age can only be an array or arguments, for example, [a, B, c] or arguments definition: apply a method of an object and replace the current object with another object. NOTE: If argArray is not a valid array or an arguments object, a TypeError occurs. If neither argArray nor thisObj is provided, the Global object will be used as thisObj and cannot be passed with any parameters.
2. Common instances
Function User (name, age) {// defines a User method this. name = function () {alert (name)}; this. age = function () {alert (age) };} function CallUser (name, age) {// For the CallUser method, add member User. call (this, name, age); // if you use apply, the value is User. apply (this, [name, age]); // User. call refers to the object to be added to this, and this refers to the current object. Of course, this can be replaced with other objects. The following name and age respectively refer to the real parameters of the User Function. // The call here is equivalent to CallUser. protype = new User ();} var us = new CallUser ("Sn", 20); // The real parameter "Sn", 20 is passed to the CallUser function. CallUser name and age are passed to User Function us. name (); // Sn us. age (); // 20
3. apply and protype
Var Class = {// create a Class Object (literally) app: function () {// create an app Class (Function) return function () {this. init. apply (this, arguments); // The current this is a function and inherits from the init attribute. The parameter is arguments }}} var pro = Class. app (); // create a Class named pro. app () assignment, (Function) pro. prototype = {init: function (arget) {// defines a member init under the pro Class, which is used to implement the init this of the Class. arget = arget;}, fn: function () {alert (this. arget) ;}} var obj = new pro ("use with protype"); obj. fn (); // result: apply and protype are used in combination.
Attachment download