Js traverses the code of the object's attribute and traverses the object's attribute. You can use the forin statement 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 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 example
Function. prototype. addMethod = function (methodName, func) {if (! This. prototype [methodName]) {this. prototype [methodName] = func; // Add a method to the prototype, which affects the 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 (va R property in obj) {if (! Obj. hasOwnProperty (property) continue; info + = property + "|";} alert (info); // name | value | toString |
For more articles about js traversal code of object attributes, refer to PHP!