hasOwnProperty在For循环中总是返​​回False

时间:2013-12-09 22:47:24

标签: javascript

我有以下

    var firstObject = {
        firstName: "James",
        lastName: "Smith",
        nationality: "American",
        age: 12,
        get_age: function(){
            return this.age;
        }
    }
    var secondObject = {
        state: "oregon",
        city: "portland"
    }
    secondObject.__proto__ = firstObject;
    for(var i in secondObject){
        if(secondObject.hasOwnProperty[i]){
            console.log(secondObject[i]);
        }
        else{
            console.log("not my own property: " + secondObject[i]);
        }
    }

secondObject从firstObject扩展。在For In循环中,州和城市应根据第一个if条件进行分类,而其他所有条件都应按else条件进行分类。当我运行上面的代码时,我的所有属性/功能都根据else条件进行分类。为什么hasOwnProperty方法在所有属性上都返回false?

1 个答案:

答案 0 :(得分:4)

.hasOwnProperty[i]    (not a property)

应该是

.hasOwnProperty(i)    (It is a method)

您应该使用括号而不是方括号