1

I'm adding a custom add() method to the Master Object.prototype so that all the generic objects will be able to access this add() method

Object.prototype.add = function(value1, value2) {
return value1 + value2;
};

Question 1 : How to check if this add() method is enumerable ?

I'm creating a generic object

var obj = {

}

I'm using for-in loop to print all the properties (this should print both own properties and prototype properties)

for (prop in obj){

    console.log("property is :" + prop);
}

This printed //property is :add

Question 2: Does for-in loop print both enumerable and non-enumerable properties?

Lets use Object.keys which returns an array of properties (only if enumerable)

var propKeys = Object.keys(obj);
console.log(propKeys); //prints an empty array []

Question 3 : why Object.keys not printing the add property?

1 Answer 1

1

To answer Question 2, a for-in loop will iterate through a property if and only if it is enumerable, so no non-enumerable properties.

To answer Question 1, in order to check if a property is enumerable, you could actually use a for-in loop, something like:

function isEnumerable(object, property) {
    for (prop in object) {  
        if (prop === property) {
            return true;
        }
    }
    return false;
}

The fact that your for-in loop prints "add" means that it is enumerable. And, in fact, all properties you define in your own code are enumerable by default.

To answer Question 3, Object.keys() will give you properties only if they are both enumerable and own properties. As .add is inherited, it won't show up using Object.keys().

Hope this helps!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.