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
-
function add(A, b)
-
{
-
return a+b;
-
}
-
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
-
var add=function (A, B
-
{
- return a+b;
-
}
-
alert1,2; //results 3 /span>
-
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
-
var add=function Theadd(A, b)
-
{
-
return a+b;
-
}
-
Alert(Add(1,2)); //Result 3
-
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
-
var myobject=New Object();
-
MyObject. add=function(a,b){returna+b};
-
MyObject now has an attribute (or method) called "Add"
-
And I can use it as follows
-
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
-
var add=New Function("A", "B", "return a+b;" );
-
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
-
Note "+"
-
And the different uses of "\"
-
var add=New Function("A", "B",
-
"alert" +
-
"(' adding ' +a+ ' and ' +b); \
-
return a+b; " );
-
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
-
function Createmyfunction(myoperator)
-
{
-
Return the new Function("A", "B", "return a" + Myoperator + "b;") );
-
}
-
-
var add=createmyfunction("+"); //Create function "Add"
-
var subtract=createmyfunction("-"); //Create function "Subtract"
-
var multiply=createmyfunction("*"); //Create function "multiply"
-
Test the functions
-
Alert("result of addition =" +add(2)); //The result is
-
Alert("Reduced result =" +subtract(2)); //The result is 8
-
Alert("result of multiplication =" +multiply(2)); //The result is
-
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
-
function ball//may look a little strange, but this declaration
- { //created an object called Ball
-
i= 1;
-
}
-
alerttypeof ball); //results "function "
-
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
-
function Ball() //may seem a little strange, but this statement
-
{ //created an object called ball, and you can
-
//reference It or add attributes to it as follows
-
Ball. callsign="the Ball"; //Add attributes to Ball
-
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
-
function MyFunction(message)
-
{
-
Alert(Message);
-
}
-
var ptr=myfunction; //PTR points to myfunction
-
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
-
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 objects
-
Object2. Saymyname=sayname;
-
Object3. Saymyname=sayname;
-
-
Object1. saymyname("Object1"); //Output "Object1"
-
Object2. saymyname("Object2"); //Output "Object2"
-
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
-
function MyFunction()
-
{
-
Alert(myfunction. Message);
-
}
-
MyFunction. message="old";
-
var ptr1=myfunction; //Ptr1 point to MyFunction
-
var ptr2=myfunction; //PTR2 also points to MyFunction
-
-
PTR1 (); //Output "old"
-
PTR2 (); //Output "old"
-
-
MyFunction. message="new";
-
-
PTR1 (); //Output "new"
-
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
-
function MyFunction()
-
{
-
Alert("old");
-
}
-
MyFunction (); //Output "old"
-
myfunction= function()
-
{
-
Alert("New");
-
};
-
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
-
function MyFunction()
-
{
-
Alert("old");
-
}
-
var savedfuncion=myfunction;
-
myfunction= function()
-
{
-
Alert("New");
-
};
-
MyFunction (); //Output "New"
-
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
-
function MyFunction()
-
{
-
Alert("old");
-
}
-
var savedfunc=myfunction;
-
savedfunc= function()
-
{
-
Alert("New");
-
};
-
MyFunction (); //Output "old"
-
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
-
function Gethalfof(NUM1, num2, num3)
-
{
-
function Calculate(number)
-
{
-
return number/2;
-
}
-
-
var result="";
-
Result+=calculate (num1) +"";
-
Result+=calculate (num2) +"";
-
Result+=calculate (num3);
-
return result ;
-
}
-
var resultstring=gethalfof(a);
-
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
-
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);
-
return result ;
-
}
-
var resultstring=gethalfof(a);
-
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
-
function Ball()
-
{
-
}
-
var ball0=New Ball(); //Ball0 now point to a new object
-
-
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
-
function Ball(message)
-
{
-
Alert(Message);
-
}
-
var ball0=New Ball("Creating new Ball"); //Create object and output message
-
Ball0. name="ball-0"; //Ball0 now has an attribute: name
-
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
-
function Ball(message)
-
{
-
Alert(Message);
-
}
-
var ball0=New Object();
-
Ball0. Construct=ball;
-
Ball0. construct("Creating new Ball"); //Execute ball0. Ball ("creating.");
-
Ball0. name="ball-0";
-
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
-
function Ball()
-
{
-
}
-
var ball0=New Ball(); //Ball0 now points to a new instance of type ball
-
Ball0. name="ball-0"; //Ball0 now has 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 giveball2添加属性name了,如果在正式的程序中这也许会引发问题。有什么好办法可以自动增加属性呢?嗯,有一个:使用this关键字。this这个词在function中有特别的意义。它指向了调用函数的那个对象。让我们看看下面的另一个示例,这时候我们在构造函数中添加上这些属性:
Example DT4
Language:javascript, parsed in:0.010 seconds, using GeSHi 1.0.7.12
-
function Ball(message, Specifiedname)
-
{
-
Alert(Message);
-
This . Name=specifiedname;
-
}
-
var ball0=New Ball("Creating new Ball", "soccer Ball");
-
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
-
function Ball(color, specifiedname, owner, weight)
-
{
-
This . Name=specifiedname;
-
This . Color=color;
-
This . Owner=owner;
-
This . weight=weight;
-
}
-
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 ""
-
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
-
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);
-
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
-
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 grow so much: ' (
-
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
-
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和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
-
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 a 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 point to the same function object, then
-
All two of the above output should be "Boss2".
-
-
Add attributes to a 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, (are: the original write is not pointing to the same function, suspected to be a clerical error)
-
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
-
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 aprototype属性,因为在每一个构造函数中都有它的存在。你可以看看下面的例子:
Example PT1
Language:javascript, parsed in:0.003 seconds, using GeSHi 1.0.7.12
-
function Test()
-
{
-
}
-
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
-
function Fish(name, color)
-
{
-
This . name=name;
-
This . Color=color;
-
}
-
Fish. prototype. livesin="Water";
-
Fish. prototype. price=;
-
Next let's make a few fish:
Language:javascript, parsed in:0.007 seconds, using GeSHi 1.0.7.12
-
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:
Language:javascript, parsed in:0.008 seconds, using GeSHi 1.0.7.12
-
For (var i=1; i<=3; i++)
-
{
-
var fish=eval("fish" +i); //I just got a pointer to the fish
-
Alert(fish. name+"," +fish. color+"," +fish. livesin+"," +fish. Price);
-
}
-
Running the sample
The output should be:
Language:text, parsed in:0.001 seconds, using GeSHi 1.0.7.12
-
"Mackarel, Gray, water, 20"
-
"Goldfish, orange, water, 20"
-
"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
-
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:
Language:javascript, parsed in:0.007 seconds, using GeSHi 1.0.7.12
-
var boss1=New Employee("Joan", 200000);
-
var boss2=New Employee("Kim", 100000);
-
var boss3=New Employee("Sam", 150000);
-
and verify it:
Language:javascript, parsed in:0.006 seconds, using GeSHi 1.0.7.12
-
Alert(Boss1. Getsalary()); //Output 200000
-
Alert(boss2. Getsalary()); //Output 100000
-
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的图表作一下对比)。