Js Code for Traversing Object Attributes

Source: Internet
Author: User
Tags hasownproperty

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 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 ){
If (! Obj. hasOwnProperty (property) continue;
Info + = property + "| ";
}
Alert (info); // name | value | toString |

Related Article

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.