For example:
Copy codeThe Code is as follows: Function. prototype. addMethod = function (methodName, func ){
If (! This. prototype [methodName]) {
This. prototype [methodName] = func; // Add a method to the prototype, which affects the type of instances.
}
Return this. prototype; // return the prototype. this type of instance can be called in a chain.
}
Function CustomObject (name, value ){
This. name = name | 'customobject ';
This. value = value | 0;
This. toString = function (){
Return '[name:' + this. name + ', value:' + this. value + ']'
}
}
CustomObject. addMethod ('testfun', function (){})
Var obj = new CustomObject ();
Var info = '';
For (var property in obj ){
Info + = property + "| ";
}
Alert (info); // name | value | toString | testFun |
However, for in also traverses the attributes of the object inherited from the prototype object. To remove the inherited attributes, use the hasOwnProperty statement. For exampleCopy codeThe Code is as follows: Function. prototype. addMethod = function (methodName, func ){
If (! This. prototype [methodName]) {
This. prototype [methodName] = func; // Add a method to the prototype, which affects the type of instances.
}
Return this. prototype; // return the prototype. this type of instance can be called in a chain.
}
Function CustomObject (name, value ){
This. name = name | 'customobject ';
This. value = value | 0;
This. toString = function (){
Return '[name:' + this. name + ', value:' + this. value + ']'
}
}
CustomObject. addMethod ('testfun', function (){})
Var obj = new CustomObject ();
Var info = '';
For (var property in obj ){
If (! Obj. hasOwnProperty (property) continue;
Info + = property + "| ";
}
Alert (info); // name | value | toString |