_javascript tips on JS function interpretation (including embedding, object, etc.)

Source: Internet
Author: User
Tags anonymous

Common wording:

function Add (a,b)

{

   return  a + b;

}

Alert (Add (1,2));    Result 3

When we define a function like this, the content of the function is compiled (but not executed immediately unless we call it). And, maybe you don't know that when this function is created, an object with the same name is created. For our example, we now have an object called "Add" (to get a closer look at the bottom function: Object section.) )

anonymous function:

We can also define it by assigning a variable name to an anonymous function.

var add = function (a,b)

{

   return  a + b;

}

Alert (Add (1,2));    Result 3

This code does the same thing as the previous example. Maybe the syntax looks strange, but it should make you feel that the function is an object, and we just assign a name to the object. You can think of it as a statement like Var myvar=[1,2,3]. The content of the function declared in this way will be compiled as well.

When we assign such a function, we do not necessarily require that it be an anonymous function. I did the same thing here, but I added the function name "Theadd" and I could refer to the function by calling the function name or the variable.

var add = function Theadd (a,b)

{return

   a + b;

}

Alert (Add (1,2));      Results 3 
alert (Theadd (1,2));    And the result is 3.

Using this method to define a function is useful in object-oriented programming, because we can make a function a property of an object like this.

var myObject = new Object ();

Myobject.add = function (a,b) {return a+b};

MyObject now has an attribute (or method) called "Add"

//And I can use it as follows

Myobject.add (1, 2);

Functions: Objects

A function is a special form of object in JavaScript. It is the first [B) class data type (Classdata type). This means that we can add attributes to it. Here are some interesting points to note

Creation of objects

As we've just mentioned, when we define a function, JavaScript actually creates an object in the background for you. The name of this object is the function name itself. The type of this object is a function. In the following example, we may not be aware of this, but we have actually created an object: it is called ball.

function Ball ()   //may seem a bit strange, but this declaration

{             //created an object called ball

   i = 1;

}

Alert (typeof ball);   Result "function"

We can even print out the contents of this object and it will output the actual code of the function.

alert (ball);  

The result is:

//function ball ()

//{

//   i = 1;

//}

Add a property

We were able to add attributes to object, including the objects function. Because the essence of defining a function is to create an object. We can "secretly" add attributes to a function. For example, we define the function ball here and add the attribute callsign.

function Ball ()   //may seem a bit strange, but this statement creates an object called Ball, and you can reference it or add 
the attribute {          

} 

ball.callsign= as follows Ball "; Add attribute 
alert (ball.callsign) to ball;//output "the ball"

Pointer

Because function is an object, we can assign a pointer to a function. In the following example, the variable PTR points to the object myfunction.

function myfunction (message) 
{ 
alert (message); 
} 
var ptr=myfunction; PTR points to myfunction 
ptr ("Hello");     The sentence will execute MyFunction: output "Hello"

We are able to run this function as if it had been replaced by the name of the pointer. So on top, this line of PTR ("Hello"); and MyFunction ("Hello"); the meaning is the same.

Pointers to functions are quite useful in object-oriented programming. For example, when we have multiple objects pointing to the same function (below):

function Sayname (name) 
{ 
alert (name); 
}

var object1=new Object ();   Create three objects 
var object2=new object (); 
var object3=new Object ();

Object1.saymyname=sayname;    Assign this function to all object 
object2.saymyname=sayname; 
Object3.saymyname=sayname;

Object1.saymyname ("Object1");  Output "Object1" 
object2.saymyname ("Object2");  Output "Object2" 
object3.saymyname ("Object3");  Output "Object3"

Because only the pointer is saved (not the function itself), when we change the function object itself, all pointers to that function will change. We can see at the bottom:

function MyFunction () 
{ 
alert (myfunction.message); 
} 
Myfunction.message= "old"; 
var ptr1=myfunction;         Ptr1 points to MyFunction 
var ptr2=myfunction;         PTR2 also points to MyFunction 
ptr1 ();           Output "old" 
ptr2 ();               Output "old" 
myfunction.message= "new"; 
PTR1 ();           Output "New" 

Pointing to the pointer

We can redistribute it after a function is created, but we need to point to the function object itself, not the pointer to it. In the following example, I will change the contents of MyFunction ().

function MyFunction () 
{ 
alert (' old '); 
} 
MyFunction (); Output "old" 
myfunction=function () 
{ 
alert ("New"); 
 

Where did the old function go?? Was abandoned.

If we need to keep it, we can assign a pointer to it before changing it.

function MyFunction () 
{ 
alert (' old '); 
} 
var savedfuncion=myfunction; 
Myfunction=function () 
{ 
alert ("New"); 
MyFunction ();  Output "New" 
savedfuncion ()//output "old"

inline function

function Get (a,b,c)

{

   function cal (n)

   {return

      N/2

   }

   var result = "";

   Result+=cal (a) + ""; 

   Result+=cal (b) + ""; 

   Result+=cal (c); 

}

var resultstring = get (10,20,30);

alert (resultstring);   Output "5 10 15"

You can only call nested functions internally. That is, you can't call this:

Gethalfof.calculate (10) because calculate only exists when the external function (Gethalfof ()) is running. This is consistent with what we discussed earlier (the function will be compiled, but it will only execute when you call it).

Which function is called?

You may be thinking about naming a conflict problem. For example, which of the following functions called calculate will be invoked?

function calculate (number) 
{return 
    number/3; 
} 
function Gethalfof (NUM1, num2, num3)   
{ 
    function calculate (number) 
    {return 
       number/2; 
    } 
    var result= ""; 
    Result+=calculate (NUM1) + ""; 
    Result+=calculate (num2) + ""; 
    Result+=calculate (num3); 
}     
var resultstring=gethalfof (10,20,30); 
alert (resultstring);     Output "5 10 15"

In this example, the compiler first searches for a local memory address, so it uses the inline calculate function. If we delete this inline (local) Calculate function, the code uses the global calculate function.

Functions: Data types and constructors

Let's look at another special feature of the function-which makes it different from other object types. A function can be used as a blueprint for a data type. This feature is typically used in object-oriented programming to simulate a user-defined data type (defined). objects created by using user-defined data types are often used as user-defined objects (defined object).

Data type

After defining a function, we also created a new data type. This data type can be used to create a new object. In the following example, I created a new data type called ball.

function Ball () 
{ 
} 
var ball0=new Ball ();//ball0 now points to a new object 
alert (ball0);     Output "Object" because Ball0 is now an object

So what does Ball0=new Ball () do? The New keyword creates a novel object (called Ball0) that is type object. It then executes ball () and passes the reference to ball0 (used to invoke the object). Below, you will see this message: "Creating new Ball" if Ball () is actually running.

function Ball (message) 
{ 
alert (message); 
} 
var ball0=new Ball ("Creating new Ball"); Create the object and output 
the message ball0.name= "ball-0";           Ball0 now has an attribute: Name 
alert (ball0.name);            Output "ball-0"

We can think of line 6th of the above code as a shorthand for the following line of code 6-8:

function Ball (message) 
{ 
alert (message); 
} 
var ball0=new Object (); 
Ball0.construct=ball; 
Ball0.construct ("Creating new ball"); Perform ball0. Ball 
("Creating."); 
Ball0.name= "ball-0";           
alert (ball0.name); 

This line of code Ball0.construct=ball is consistent with the ptr=myfunction syntax in the above.

Add properties

When we use the keyword new to create an object like the one above, the new object is created. We can add attributes to this object after we create it (as if I added attribute name to the above). And the next problem is that if we create another instance of this object, we have to add this property again to the new object as follows. )

function Ball () 
{ 
} 
var ball0=new Ball ();//ball0 now points to a new instance of type Ball ball0.name= 
"ball-0";//Ball0 There is now a property "name" 
var ball1=new Ball (); 
Ball1.name= "Ball-1"; 
var ball2=new Ball (); 
alert (ball0.name);  Output "ball-0" 
alert (ball1.name);  Output "BALL-1" 
alert (ball2.name);  Oh, I forgot to add "name" to Ball2!

I forgot to add attribute name to BALL2, which may cause problems in a formal program. Is there any good way to automatically add attributes? Well, there's one: use the This keyword. This word has a special meaning in function. It points to the object that called the function. Let's look at another example below, when we add these properties to the constructor:

function Ball (message, specifiedname) 
{ 
alert (message); 
this.name=specifiedname;        
} 
var ball0=new Ball ("Creating New Ball", "soccer Ball"); 
alert (ball0.name);          Prints "Soccer Ball"

Keep in mind that the New keyword eventually makes the constructor execute. In this example, it will run Ball ("Creating New Ball", "Soccer Ball"), and the keyword this will point to ball0.

Therefore, this line: This.name=specifiedname became ball0.name= "soccer Ball". It basically says: Add attribute name to Ball0, soccer Ball is the property value.

We're just adding a name attribute to Ball0, which looks like it did in the previous example, but it's a better and more extensible approach. Now we can create a lot of ball with attributes without having to add them manually. Also, people want to create a ball object that clearly understands its constructor and can easily find all the properties of ball. Let's add more attributes to the ball.

function Ball (color, specifiedname, owner, weight) 
{ 
this.name=specifiedname;        
This.color=color; 
This.owner=owner; 
this.weight=weigth; 
} 
var ball0=new Ball ("Black/white", "Soccer Ball", "John"); 
var ball1=new Ball ("Gray", "Bowling Ball", "John"); 
var ball2=new Ball ("Yellow", "Golf Ball", "John"); 
var balloon=new Ball ("Red", "balloon", "Pete"); 
alert (ball0.name);            Output "Soccer Ball" 
alert (balloon.name);           Output "Balloon" 
alert (ball2.weight);           Output "55"

Hey! Using object-oriented terminology, you can say that ball is an object type that has the following attributes: Name,color, owner, weight.

Assigning objects to attributes we're not restricted. You can only add simple data types, such as strings or numbers, as attributes. We can also assign objects to attributes. Below, supervisor is an attribute of employee.

function Employee (name, salary, Mysupervisor) 
{ 
this.name=name;        
This.salary=salary; 
this.supervisor=mysupervisor; 
} 
var boss=new Employee ("John"); 
var manager=new Employee ("Joan", boss); 
var teamleader=new Employee ("Rose", boss); 
Alert (manager.supervisor.name+ "is the supervisor of" +manager.name); 
Alert (manager.name+ "\ S supervisor is" +manager.supervisor.name);

A function is also an object. So you can make a function as an attribute of an object. Next, I'll add two functions getsalary and addsalary.

 function Employee (name, salary) {this.name=name; 
This.salary=salary; 
This.addsalary=addsalaryfunction; 
         This.getsalary=function () {return this.salary; 
}; 
function Addsalaryfunction (addition) {this.salary=this.salary+addition; 
} var boss=new Employee ("John", 200000);          Boss.addsalary (10000); Boss Long 10K Salary ...         Why bosses ' wages can be so much longer: ' (Alert (boss.getsalary ()); Output 210K ...

Why is the default wage so high ...: ' (Addsalary and getsalary demonstrate several different ways to assign a function to a property.

As mentioned in the previous several times, the result of a function declaration is that an object is created.        
function Employee (name, salary) {this.name=name; 
This.salary=salary; 
This.addsalary=addsalaryfunction; 
         This.getsalary=function () {return this.salary; 
}; 
function Addsalaryfunction (addition) {this.salary=this.salary+addition; 
} var boss=new Employee ("John", 200000); 
var boss2=new Employee ("Joan", 200000); 
var boss3=new Employee ("Kim", 200000); 

When you create more instances of this object (Boss2 and BOSS3), each instance has a separate copy of the getsalary code; instead, addsalary points to the same place (that is, addsalaryfunction).

Look at the following code to understand what is described above.

function Employee (name, salary) 
{ 
this.name=name;        
This.salary=salary; 
this.addsalary=addsalaryfunction; 
This.getsalary=function () 
         {return 
          this.salary;} 
         ; 
} function Addsalaryfunction (addition) 
{ 
this.salary=this.salary+addition; 
} 
var boss1=new Employee ("John", 200000); 
var boss2=new Employee ("Joan", 200000);

Add attributes to the Getsalary function object 
boss1.getsalary.owner= "Boss1"; 
Boss2.getsalary.owner= "Boss2"; 
alert (boss1.getSalary.owner);  Output "Boss1" 
alert (boss2.getSalary.owner);  Output "Boss2" 
///If two objects are pointing to the same function object, all two of the above outputs should be "Boss2". 
//To add attributes to the Addsalary function object 
boss1.addsalary.owner= "Boss1"; 
Boss1.addsalary.owner= "Boss2"; 
alert (boss1.addSalary.owner);  Output "Boss2" 
alert (boss2.addSalary.owner);  Output "Boss2"

///Because two objects all point to the same function

//When modifying one of them, it affects all instances (so all two output "Boss2").

It may not be important, but here are some conclusions about running inline functions similar to the getsalary above:

1 requires more storage space to store objects (because each object instance will have its own getsalary code copy);

2 JavaScript requires more time to construct this object.

Let's write the example again to make it more efficient.

function Employee (name, salary) 
{ 
this.name=name;        
This.salary=salary; 
this.addsalary=addsalaryfunction; 
this.getsalary=getsalaryfunction; 
} 
function getsalaryfunction () 
{return 
this.salary; 
} 
function Addsalaryfunction (addition) 
{ 
this.salary=this.salary+addition; 
}

Look here, all two functions point to the same place, which will save space and shorten the construction time (especially if you have a whole bunch of inline functions in a constructor). Here's another function that will be able to promote this design, which is called prototype, and we'll discuss it in the next section.

Functions: Prototypes

Each constructor has a property called a prototype (prototype, which is no longer translated, uses its original text). This property is useful: declaring a generic variable or function for a particular class.

Definition of prototype

You don't have to explicitly declare a prototype attribute because it exists in every constructor. You can look at the following example:

function Test () 
{ 
} 
alert (test.prototype);//Output "Object"

Add attributes to Prototype

As you can see above, prototype is an object, so you are able to add attributes to it. The attributes you add to the prototype will become common properties of the objects created using this constructor.

For example, I have a data type below. Fish, I want to make all the fishes have these attributes:

livesin= "Water" and price=20; To achieve this, I can add those attributes to the prototype of the constructor fish.

function Fish (name, color) 
{ 
this.name=name; 
This.color=color; 
} 
fish.prototype.livesin= "Water"; 
fish.prototype.price=20; 

Next let's make a few fish:

var fish1=new Fish ("Mackarel", "Gray"); 
var fish2=new Fish ("Goldfish", "orange"); 
var fish3=new Fish ("Salmon", "white");

Let's take a look at the properties of the fish:

for (int i=1; i<=3; i++) 
{ 
var fish=eval ("Fish" +i);  I just got the pointer to this fish, 
alert (fish.name+ "," +fish.color+ "," +fish.livesin+ "," +fish.price "); 
 

The output should be:

"Mackarel, Gray, Water," " 
goldfish, orange, water," 
"salmon, white water, 20"

You see all the fish have attributes livesin and price, we don't even specifically declare these attributes for each different fish. This is because when an object is created, the constructor assigns its attribute prototype to the internal property __proto__ of the new object. This __proto__ is used by this object to find its properties.

You can also add a shared function to all objects by prototype. Here's a good thing: you don't have to create and initialize this function every time you construct an object.

Add a function to an object with prototype

function Employee (name, salary) 
{ 
this.name=name;        
this.salary=salary; 
} 
Employee.prototype.getsalary=function getsalaryfunction () 
{return 
this.salary; 
} 
Employee.prototype.addsalary=function addsalaryfunction (addition) 
{ 
this.salary=this.salary+addition; 
}

We can create objects like we usually do:

var boss1=new Employee ("Joan", 200000); 
var boss2=new Employee ("Kim", 100000); 
var boss3=new Employee ("Sam", 150000); 

and verify it:

Alert (Boss1.getsalary ());  Output 200000 
alert (boss2.getsalary ());  Output 100000 
alert (Boss3.getsalary ());  Output 150000

Here is a diagram to illustrate how prototype works. Each instance of this object (Boss1, Boss2, BOSS3) has an internal property called __proto__, which points to the property prototype of its constructor (Employee). When you perform getsalary or addsalary, the object will find and execute the code in its __proto__.

The above about JS function interpretation (including embedded, object, etc.) is small to share all the content of everyone, hope to give you a reference, but also hope that we support the cloud habitat community.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.