当前位置:编程学习 > asp >>

给一个类增加属性和方法?看看这个够不够?

答案:prototype
Represents the prototype for this class. You can use the prototype to add properties or methods to all instances of a class. For information on prototypes, see Function.prototype.Property of
String

Implemented in
javascript 1.1, NES 3.0

ECMA version
ECMA-262


prototype
A value from which instances of a particular class are created. Every object that can be created by calling a constructor function has an associated prototype property.Property of
Function

Implemented in
javascript 1.1, NES 2.0

ECMA version
ECMA-262



Description
You can add new properties or methods to an existing class by adding them to the prototype associated with the constructor function for that class. The syntax for adding a new property or method is:

fun.prototype.name = value
wherefun
The name of the constructor function object you want to change.

name
The name of the property or method to be created.

value
The value initially assigned to the new property or method.



If you add a property to the prototype for an object, then all objects created with that object's constructor function will have that new property, even if the objects existed before you created the new property. For example, assume you have the following statements:

var array1 = new Array();var array2 = new Array(3);Array.prototype.description=null;array1.description="Contains some stuff"array2.description="Contains other stuff"
After you set a property for the prototype, all subsequent objects created with Array will have the property:

anotherArray=new Array()anotherArray.description="Currently empty"
Example
The following example creates a method, str_rep, and uses the statement String.prototype.rep = str_rep to add the method to all String objects. All objects created with new String() then have that method, even objects already created. The example then creates an alternate method and adds that to one of the String objects using the statement s1.rep = fake_rep. The str_rep method of the remaining String objects is not altered.

var s1 = new String("a")var s2 = new String("b")var s3 = new String("c")
// Create a repeat-string-N-times method for all String objectsfunction str_rep(n) {   var s = "", t = this.toString()   while (--n >= 0) s += t   return s}
String.prototype.rep = str_rep
s1a=s1.rep(3) // returns "aaa"s2a=s2.rep(5) // returns "bbbbb"s3a=s3.rep(2) // returns "cc"
// Create an alternate method and assign it to only one String variablefunction fake_rep(n) {   return "repeat " + this + " " + n + " times."}
s1.rep = fake_reps1b=s1.rep(1) // returns "repeat a 1 times."s2b=s2.rep(4) // returns "bbbb"s3b=s3.rep(6) // returns "cccccc"
The function in this example also works on String objects not created with the String constructor. The following code returns "zzz".

"z".rep(3)

上一个:易做图下拉框连动的数据库版!
下一个:在网页中实现OICQ里的头像选择的下拉框 (附例子)

CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,