The function _javascript techniques of javascript

Source: Internet
Author: User
Tags anonymous constructor

Functions of JavaScript

    • Author: F. Permadi
    • Translator: Sheneyan (Zi Wu)
    • Time: 2006.01.03
    • English Original: INTRODUCTION to JavaScript functions

Sub-note: A pretty good entry for function, personal feeling is quite classic.

Word translation List
function: Functions (functional not translated)
Declare: Defining
assign: assigning, assigning
functionbody: Function body (is the content of the function)
Object: Objects
Property: Properties
unnamed: Anonymous (not translated here to unnamed)
Object Oriented Programming: Surface relative Phase programming
Class
: Classes (such as the later class data type I translate into class datatype)
pointer: Pointers
Reassign: reassigning
Nest: Nesting
feature: Functions,
features
Local/global: Local/Global
Blueprint: Blueprint (?
User defined: Custom
instance: instance
prototype: prototype (except title not translated) in
Ternal: Internal
Constructor: constructor
duplication: copying

Functions: Defining

There are several ways in which you can define a function. All of these are valid, but there are some differences in how they are implemented in the background.

Commonly used in the drafting

In general, we use this notation to define a function:

functionName([parameters]){functionBody};

Example D1:

Language:javascript, parsed in:0.005 seconds, using GeSHi 1.0.7.12
    1. function add(A, b)
    2. {
    3. return a+b;
    4. }
    5. Alert(Add(1,2)); //Result 3

Running the sample

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 functions

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

Example D2

Language:javascript, parsed in:0.006 seconds, using GeSHi 1.0.7.12
    1. var add=function (A, B
    2. {                     
    3.   return a+b;
    4. }                     
    5. alert1,2;        //results 3 /span>
    6.  

Running the sample

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 pair. You can think of it var myVar=[1,2,3] as the same sentence. 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. Here, I made andExampleD2一样的事情,但我加了函数名“theAdd”,而且我可以通过调用函数名或者是那个变量来引用函数。

Example D2A

Language:javascript, parsed in:0.008 seconds, using GeSHi 1.0.7.12
  1. var add=function Theadd(A, b)
  2. {
  3. return a+b;
  4. }
  5. Alert(Add(1,2)); //Result 3
  6. Alert(Theadd(1,2)); //The result is also 3

Running the sample

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.

Language:javascript, parsed in:0.005 seconds, using GeSHi 1.0.7.12
    1. var myobject=New Object();
    2. MyObject.  add=function(a,b){returna+b};
    3. MyObject now has an attribute (or method) called "Add"
    4. And I can use it as follows
    5. MyObject. Add(1, 2);

New

We can also use operators tonew来定义一个函数。

This is one of the most unusual ways to define a function and is not recommended in this way unless there are special reasons (see below for possible reasons). The syntax is as follows:

varName=new Function([param1Name, param2Name,...paramNName], functionBody);

Example D3:

Language:javascript, parsed in:0.004 seconds, using GeSHi 1.0.7.12
  1. var add=New Function("A", "B", "return a+b;" );
  2. Alert(Add(3,4)); //Result 7

Running the sample

I have two parameters here calleda和b,而函数体返回a和b的和。请注意new Function(...)使用了大写F,而不是小写f。 这就告诉javascript,我们将要创建一个类型是Function的对象。 还要注意到,参数名和函数体都是作为字符串而被传递。我们可以随心所欲的增加参数,javascript知道函数体会是右括号前的最后一个字符串(如果没有参数,你能够只写函数体)。你没必要将所有东西都写在一行里(使用\或者使用字符串连接符+来分隔长代码)。\标记告诉JavaScript在下一行查找字符串的其余部分。例子如下:

Example D4

Language:javascript, parsed in:0.007 seconds, using GeSHi 1.0.7.12
  1. Note "+"
  2. And the different uses of "\"
  3. var add=New Function("A", "B",
  4. "alert" +
  5. "(' adding ' +a+ ' and ' +b); \
  6. return a+b; " );
  7. Alert(Add(3,4)); //Result 7

Javascript:exampled4 ();

Defining a function in this way causes the function not to be compiled, and it may be slower than a function defined in other ways. As for why, take a look at this code:

Example D5

Language:javascript, parsed in:0.022 seconds, using GeSHi 1.0.7.12
  1. function Createmyfunction(myoperator)
  2. {
  3. Return the new Function("A", "B", "return a" + Myoperator + "b;") );
  4. }
  5. var add=createmyfunction("+"); //Create function "Add"
  6. var subtract=createmyfunction("-"); //Create function "Subtract"
  7. var multiply=createmyfunction("*"); //Create function "multiply"
  8. Test the functions
  9. Alert("result of addition =" +add(2)); //The result is
  10. Alert("Reduced result =" +subtract(2)); //The result is 8
  11. Alert("result of multiplication =" +multiply(2)); //The result is
  12. Alert(add);

Running the sample

This interesting example creates three different functionand creates a new functionby passing different parameters in real time. Because the compiler has no way of knowing what the final code will look like, new Function(...) the content is not compiled. So what's the good of that? Well, for example, this might be useful if you need users to be able to create their own functions, such as in a game. We may need to allow the user to add "behavior" to a "player". But again, in general, we should avoid using this form unless there is a special purpose.

Functions: Objects

A function is a special form of object in JavaScript. It is the first class data 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 calledBall。

Example 1

Language:javascript, parsed in:0.006 seconds, using GeSHi 1.0.7.12
    1. function ball//may look a little strange, but this declaration
    2. {                     //created an object called Ball
    3.   i= 1;
    4. }                     
    5. alerttypeof ball);     //results "function "
    6.  

Running the sample

We can even print out the contents of this object and it will output the actual code for this function, Example 2: Click Alert (Ball);Ball的内容。

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 a function hereBall,并添加属性callsign。

Language:javascript, parsed in:0.007 seconds, using GeSHi 1.0.7.12
  1. function Ball() //may seem a little strange, but this statement
  2. { //created an object called ball, and you can
  3. //reference It or add attributes to it as follows
  4. Ball. callsign="the Ball"; //Add attributes to Ball
  5. Alert(Ball. Callsign); //Output "The Ball"

Running the sample

Pointer

Because function is an object, we can assign a pointer to a function . In the following example, the variableptr指向了对象myFunction。

Language:javascript, parsed in:0.005 seconds, using GeSHi 1.0.7.12
    1. function MyFunction(message)
    2. {
    3. Alert(Message);
    4. }
    5. var ptr=myfunction; //PTR points to myfunction
    6. PTR ("Hello"); //This will execute MyFunction: output "Hello"

Running the sample

We are able to run this function as if it had been replaced by the name of the pointer. So on top, this line 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):

Example 4 A

Language:javascript, parsed in:0.017 seconds, using GeSHi 1.0.7.12
  1. function Sayname(name)
  2. {
  3. Alert(name);
  4. }
  5. var object1=New Object(); //Create three objects
  6. var object2=New Object();
  7. var object3=New Object();
  8. Object1.        Saymyname=sayname; //Assign this function to all objects
  9. Object2. Saymyname=sayname;
  10. Object3. Saymyname=sayname;
  11. Object1.    saymyname("Object1"); //Output "Object1"
  12. Object2.    saymyname("Object2"); //Output "Object2"
  13. Object3.    saymyname("Object3"); //Output "Object3"

Running the sample

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:

Example 5:

Language:javascript, parsed in:0.016 seconds, using GeSHi 1.0.7.12
  1. function MyFunction()
  2. {
  3. Alert(myfunction. Message);
  4. }
  5. MyFunction. message="old";
  6. var ptr1=myfunction; //Ptr1 point to MyFunction
  7. var ptr2=myfunction; //PTR2 also points to MyFunction
  8. PTR1 (); //Output "old"
  9. PTR2 (); //Output "old"
  10. MyFunction. message="new";
  11. PTR1 (); //Output "new"
  12. PTR2 (); //Output "new"

Running the sample

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 changemyfunction()的内容。

Example 6:

Language:javascript, parsed in:0.007 seconds, using GeSHi 1.0.7.12
  1. function MyFunction()
  2. {
  3. Alert("old");
  4. }
  5. MyFunction (); //Output "old"
  6. myfunction= function()
  7. {
  8. Alert("New");
  9. };
  10. MyFunction (); //Output "New"

Running the sample

Where did the old function go?? Was abandoned.

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

Example 6 A:

Language:javascript, parsed in:0.008 seconds, using GeSHi 1.0.7.12
  1. function MyFunction()
  2. {
  3. Alert("old");
  4. }
  5. var savedfuncion=myfunction;
  6. myfunction= function()
  7. {
  8. Alert("New");
  9. };
  10. MyFunction (); //Output "New"
  11. Savedfuncion (); //Output "old"

Running the sample

But be careful, examples like the one below do not work because you create another one calledmyFunctionPtr的函数而不是修改它。

Example 6 B:

Language:javascript, parsed in:0.009 seconds, using GeSHi 1.0.7.12
  1. function MyFunction()
  2. {
  3. Alert("old");
  4. }
  5. var savedfunc=myfunction;
  6. savedfunc= function()
  7. {
  8. Alert("New");
  9. };
  10. MyFunction (); //Output "old"
  11. Savedfunc (); //Output "New"

Running the sample

inline function

We also have the ability to nest a function in a function . The following example, I have a name calledgetHalfOf的函数,而在它里面,我有另一个叫做calculate的函数。

Example 7

Language:javascript, parsed in:0.015 seconds, using GeSHi 1.0.7.12
  1. function Gethalfof(NUM1, num2, num3)
  2. {
  3. function Calculate(number)
  4. {
  5. return number/2;
  6. }
  7. var result="";
  8. Result+=calculate (num1) +"";
  9. Result+=calculate (num2) +"";
  10. Result+=calculate (num3);
  11. return result ;
  12. }
  13. var resultstring=gethalfof(a);
  14. Alert(resultstring); //Output "5"

Running the sample

You can only call nested functions internally. That is, you can't call that: getHalfOf.calculate(10) becausecalculate只有当外部函数(getHalfOf())在运行的时候才会存在。这和我们前面的讨论一致(函数会被编译,但只有当你去调用它的时候才会执行)。

Which function is called?

You may be thinking about naming a conflict problem. For example, which one of the following is calledcalculate的函数会被调用?

Example 8

Language:javascript, parsed in:0.017 seconds, using GeSHi 1.0.7.12
  1. function Calculate(number)
  2. {
  3. Return number/3;
  4. }
  5. function Gethalfof(NUM1, num2, num3)
  6. {
  7. function Calculate(number)
  8. {
  9. return number/2;
  10. }
  11. var result="";
  12. Result+=calculate (num1) +"";
  13. Result+=calculate (num2) +"";
  14. Result+=calculate (num3);
  15. return result ;
  16. }
  17. var resultstring=gethalfof(a);
  18. Alert(resultstring); //Output "5"

Running the sample

In this example, the compiler will first search for the local memory address, so it uses the embeddedcalculate函数。如果我们删除了这个内嵌(局部)的calculate函数,这个代码会使用全局的calculate函数。

Functions: Data types and constructors

Let's look at another special feature of a 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 name calledBall的新数据类型。

Example DT1

Language:javascript, parsed in:0.004 seconds, using GeSHi 1.0.7.12
    1. function Ball()
    2. {
    3. }
    4. var ball0=New Ball(); //Ball0 now point to a new object
    5. Alert(ball0); //Output "Object", because Ball0 is now an object

Running the sample

So, what does it look like ball0=new Ball() ? The new keyword creates a type that isObject的新对象(叫做ball0)。然后它会执行Ball(),并将这个引用传给ball0(用于调用对象)。下面,你会看到这条消息:“creating new Ball”,如果Ball()实际上被运行的话。

Example DT2

Language:javascript, parsed in:0.009 seconds, using GeSHi 1.0.7.12
  1. function Ball(message)
  2. {
  3. Alert(Message);
  4. }
  5. var ball0=New Ball("Creating new Ball"); //Create object and output message
  6. Ball0.                      name="ball-0"; //Ball0 now has an attribute: name
  7. Alert(ball0.                         Name); //Output "ball-0"

Running the sample

We can think of the highlighted line in the above code as a shorthand for the following code highlights:

Language:javascript, parsed in:0.010 seconds, using GeSHi 1.0.7.12
  1. function Ball(message)
  2. {
  3. Alert(Message);
  4. }
  5. var ball0=New Object();
  6. Ball0. Construct=ball;
  7. Ball0.  construct("Creating new Ball"); //Execute ball0. Ball ("creating.");
  8. Ball0.                      name="ball-0";
  9. Alert(ball0.          Name);

Running the sample

This line of code is ball0.construct=Ball consistent with the syntax in Example 4 ptr=myFunction .

If you still don't understand the meaning of this line, go back and review Example 4. Note: You may consider running directly ball0.Ball("...") , but it will not work becauseball0并没有一个叫做Ball("...")的属性,并且它也不知道你究竟想作些什么。

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 the attribute on the top)name。而接下来的问题就是如果我们创建了这个对象的另外一个实例,我们得象下面那样再次给这个新对象添加这个属性。)

Example DT3 (creates 3 ball objects)

Language:javascript, parsed in:0.013 seconds, using GeSHi 1.0.7.12
  1. function Ball()
  2. {
  3. }
  4. var ball0=New Ball(); //Ball0 now points to a new instance of type ball
  5. Ball0.  name="ball-0"; //Ball0 now has a property "name"
  6. var ball1=New Ball();
  7. Ball1. name="Ball-1";
  8. var ball2=New Ball();
  9. Alert(ball0.     Name); //Output "ball-0"
  10. Alert(ball1.     Name); //Output "BALL-1"
  11. Alert(ball2.     Name); //Oh, I forgot to add "name" to Ball2!

I forgot to giveball2添加属性name了,如果在正式的程序中这也许会引发问题。有什么好办法可以自动增加属性呢?嗯,有一个:使用this关键字。this这个词在function中有特别的意义。它指向了调用函数的那个对象。让我们看看下面的另一个示例,这时候我们在构造函数中添加上这些属性:

Example DT4

Language:javascript, parsed in:0.010 seconds, using GeSHi 1.0.7.12
  1. function Ball(message, Specifiedname)
  2. {
  3. Alert(Message);
  4. This .                Name=specifiedname;
  5. }
  6. var ball0=New Ball("Creating new Ball", "soccer Ball");
  7. Alert(ball0.                    Name); //Prints "soccer Ball"

Running the sample

Keep in mind that the new keyword eventually makes the constructor execute. In this case, it will run and the Ball("creating new Ball", "Soccer Ball"); keyword this will point toball0。

So, this line: this.name=specifiedName turned into a ball0.name="Soccer Ball" .

It mainly says: Giveball0添加属性name,属性值是Soccer Ball

We are now just adding aname属性给ball0,看起来和上一个例子中所做的很象,但却是一个更好更具扩展性的方法。现在,我们可以随心所欲的创建许多带有属性的ball而无需我们手动添加它们。而且,人们也希望创建的Ball对象能够清晰的看懂它的构造函数并且能够轻松找出Ball的所有属性。让我们添加更多属性到Ball里。

Example DT5

Language:javascript, parsed in:0.026 seconds, using GeSHi 1.0.7.12
  1. function Ball(color, specifiedname, owner, weight)
  2. {
  3. This .                Name=specifiedname;
  4. This . Color=color;
  5. This . Owner=owner;
  6. This . weight=weight;
  7. }
  8. var ball0=New Ball("Black/white", "soccer Ball", "John" );
  9. var ball1=New Ball("Gray", "Bowling Ball", "John" );
  10. var ball2=New Ball("Yellow", "Golf Ball", "John" );
  11. var balloon=New Ball("Red", "balloon", "Pete" );
  12. Alert(ball0.                         Name); //output "soccer Ball"
  13. Alert(balloon.                       Name); //Output "Balloon"
  14. Alert(ball2.                       Weight); //Output ""

Running the sample

Hey! With object-oriented terminology, you can sayBall是一个拥有如下属性的对象类型:name, color, owner, weight。

Assigning an object to a property

We're not restricted. Only simple data types, such as strings or numbers, can be added as attributes. We can also assign objects to attributes. Belowsupervisor是Employee的一个属性.

Example DT6

Language:javascript, parsed in:0.021 seconds, using GeSHi 1.0.7.12
  1. function Employee(name, salary, Mysupervisor)
  2. {
  3. This .                name=name;
  4. This . salary=salary;
  5. This . supervisor=mysupervisor;
  6. }
  7. var boss=New Employee("John" );
  8. var manager=New Employee("Joan", boss);
  9. var teamleader=New Employee("Rose", boss);
  10. Alert(manager. Supervisor. name+"is the supervisor of" +manager. Name);
  11. Alert(manager. name+"\ S Supervisor is" +manager. Supervisor.  name);

What will it output? Running the sample

As you can see in the example above,manager和teamLeader都有一个supervisor属性,而这个属性是类型Employee的一个对象。

To use a function as a property

Any type of object can be used as a property, recall the previous example 4 (not example DT4), and the function is an object. So you can make a function as an attribute of an object. Next, I'll add two functionsgetSalary和addSalary。

Example DT7

Language:javascript, parsed in:0.022 seconds, using GeSHi 1.0.7.12
  1. function Employee(name, salary)
  2. {
  3. This .                name=name;
  4. This . salary=salary;
  5. This . addsalary=addsalaryfunction;
  6. This . getsalary=function()
  7. {
  8. return this . Salary;
  9. };
  10. }
  11. function Addsalaryfunction(addition)
  12. {
  13. This . salary= this. salary+addition;
  14. }
  15. var boss=New Employee("John", 200000);
  16. Boss.                    addsalary(10000); //Boss Long 10K salary ... Why bosses ' wages can grow so much: ' (
  17. Alert(boss.                   Getsalary()); //Output 210K ... Why is the default wage so high ...: ' (

Running the sample

addSalary和getSalary演示了几种将函数赋给属性的不同方法。如果你记得我们最开始的讨论;我讨论了三种声明函数的不同方式。所有那些在这里都是适用的,但是上面展示的两个最常用。

Let's see what's different. Next, take a look at 9-12 lines of code. When this part of the code executes, the functiongetSalary被声明。如前面数次提到的,一个函数声明的结果是一个对象被创建。所以这时候boss被创建(接下来的高亮行),而boss里有一个getSalary属性。

Language:javascript, parsed in:0.022 seconds, using GeSHi 1.0.7.12
  1. function Employee(name, salary)
  2. {
  3. This .                name=name;
  4. This . salary=salary;
  5. This . addsalary=addsalaryfunction;
  6. This . getsalary=function()
  7. {
  8. return this . Salary;
  9. };
  10. }
  11. function Addsalaryfunction(addition)
  12. {
  13. This . salary= this. salary+addition;
  14. }
  15. var boss=New Employee("John", 200000);
  16. var boss2=New Employee("Joan", 200000);
  17. var boss3=New Employee("Kim", 200000);

When you create more instances of this object (boss2和boss3),每一个实例都有一份getSalary代码的单独拷贝;而与此相反,addSalary则指向了同一个地方(即addSalaryFunction)。

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

Example DT8

Language:javascript, parsed in:0.036 seconds, using GeSHi 1.0.7.12
  1. function Employee(name, salary)
  2. {
  3. This .                name=name;
  4. This . salary=salary;
  5. This . addsalary=addsalaryfunction;
  6. This . getsalary=function()
  7. {
  8. return this . Salary;
  9. };
  10. }
  11. function Addsalaryfunction(addition)
  12. {
  13. This . salary= this. salary+addition;
  14. }
  15. var boss1=New Employee("John", 200000);
  16. var boss2=New Employee("Joan", 200000);
  17. Add attributes to a Getsalary function object
  18. Boss1. getsalary. owner="Boss1";
  19. Boss2. getsalary. owner="Boss2";
  20. Alert(Boss1. Getsalary.   owner); //Output "Boss1"
  21. Alert(boss2. Getsalary.   owner); //Output "Boss2"
  22. If two objects point to the same function object, then
  23. All two of the above output should be "Boss2".
  24. Add attributes to a Addsalary function object
  25. Boss1. addsalary. owner="Boss1";
  26. Boss1. addsalary. owner="Boss2";
  27. Alert(Boss1. Addsalary.   owner); //Output "Boss2"
  28. Alert(boss2. Addsalary.   owner); //Output "Boss2"
  29. Because two objects all point to the same function, (are: the original write is not pointing to the same function, suspected to be a clerical error)
  30. When you modify one of these, all instances are affected (so two outputs "Boss2").

Running the sample

Maybe that's not the important thing but here are some about running like abovegetSalary的内嵌函数的结论: 1) 需要更多的存储空间来存储对象(因为每一个对象实例都会有它自己的getSalary代码拷贝);2) javascript需要更多时间来构造这个对象。

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

Example DT9

Language:javascript, parsed in:0.014 seconds, using GeSHi 1.0.7.12
  1. function Employee(name, salary)
  2. {
  3. This .                name=name;
  4. This . salary=salary;
  5. This . addsalary=addsalaryfunction;
  6. This . getsalary=getsalaryfunction;
  7. }
  8. function Getsalaryfunction()
  9. {
  10. return this . Salary;
  11. }
  12. function Addsalaryfunction(addition)
  13. {
  14. This . salary= this. salary+addition;
  15. }

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 aprototype属性,因为在每一个构造函数中都有它的存在。你可以看看下面的例子:

Example PT1

Language:javascript, parsed in:0.003 seconds, using GeSHi 1.0.7.12
  1. function Test()
  2. {
  3. }
  4. Alert(Test.prototype); //Output "Object"

Running the sample

Add attributes to Prototype

As you can see on the above,prototype是一个对象,因此,你能够给它添加属性。你添加给prototype的属性将会成为使用这个构造函数创建的对象的通用属性。

For example, I have a data type belowFish,我想让所有的鱼都有这些属性:livesIn="water"price=20;为了实现这个,我可以给构造函数Fish的prototype添加那些属性。

Example PT2

Language:javascript, parsed in:0.007 seconds, using GeSHi 1.0.7.12
  1. function Fish(name, color)
  2. {
  3. This . name=name;
  4. This . Color=color;
  5. }
  6. Fish. prototype. livesin="Water";
  7. Fish. prototype. price=;

Next let's make a few fish:

Language:javascript, parsed in:0.007 seconds, using GeSHi 1.0.7.12
  1. var fish1=New Fish("Mackarel", "Gray");
  2. var fish2=New Fish("Goldfish", "Orange");
  3. var fish3=New Fish("Salmon", "white");

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

Language:javascript, parsed in:0.008 seconds, using GeSHi 1.0.7.12
  1. For (var i=1; i<=3; i++)
  2. {
  3. var fish=eval("fish" +i); //I just got a pointer to the fish
  4. Alert(fish. name+"," +fish. color+"," +fish. livesin+"," +fish. Price);
  5. }

Running the sample

The output should be:

Language:text, parsed in:0.001 seconds, using GeSHi 1.0.7.12
  1. "Mackarel, Gray, water, 20"
  2. "Goldfish, orange, water, 20"
  3. "Salmon, white water, 20"

You see all the fish have attributeslivesIn和price,我们甚至都没有为每一条不同的鱼特别声明这些属性。这时因为当一个对象被创建时,这个构造函数将会把它的属性prototype赋给新对象的内部属性__proto__。这个__proto__被这个对象用来查找它的属性。

Add a function to an object with prototype

You can also passprototype来给所有对象添加共用的函数。这有一个好处:你不需要每次在构造一个对象的时候创建并初始化这个函数。为了解释这一点,让我们重新来看Example DT9并使用prototype来重写它:

Example PT3

Language:javascript, parsed in:0.013 seconds, using GeSHi 1.0.7.12
  1. function Employee(name, salary)
  2. {
  3. This .                name=name;
  4. This . salary=salary;
  5. }
  6. Employee. prototype. getsalary=function getsalaryfunction()
  7. {
  8. return this . Salary;
  9. }
  10. Employee. prototype. addsalary=function addsalaryfunction(addition)
  11. {
  12. This . salary= this. salary+addition;
  13. }

We can create objects like we usually do:

Language:javascript, parsed in:0.007 seconds, using GeSHi 1.0.7.12
  1. var boss1=New Employee("Joan", 200000);
  2. var boss2=New Employee("Kim", 100000);
  3. var boss3=New Employee("Sam", 150000);

and verify it:

Language:javascript, parsed in:0.006 seconds, using GeSHi 1.0.7.12
    1. Alert(Boss1.    Getsalary()); //Output 200000
    2. Alert(boss2.    Getsalary()); //Output 100000
    3. Alert(BOSS3.    Getsalary()); //Output 150000

Running the sample

Here is a diagram to illustrateprototype是如何工作的。这个对象的每一个实例(boss1, boss2, boss3)都有一个内部属性叫做__proto__,这个属性指向了它的构造器(Employee)的属性prototype。当你执行getSalary或者addSalary的时候,这个对象会在它的__proto__找到并执行这个代码。注意这点:这里并没有代码的复制(和Example DT8的图表作一下对比)。

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.