对象方法可以有自己的属性

Can object method have own propertis?

本文关键字:自己的 属性 方法 对象      更新时间:2023-09-26

对于函数,我可以这样做:

uniqueInteger.counter = 0;
function uniqueInteger() {
    return uniqueInteger.counter++; // Increment and return counter property
}

我也可以使用对象方法执行此操作吗?

是的,你可以,因为函数是第一类对象:

在 JavaScript 中,函数是一等对象,因为它们可以像任何其他对象一样具有属性和方法。它们与其他对象的区别在于可以调用函数。简而言之,它们是函数对象。

var object = {
        x: function () { return this.x.value; }
    };
object.x.value = 42;
document.write(object.x());

对象方法是函数。您可以对任何函数执行此操作:

var a = function () { }
a.bar = "f";
for(property in a) {
 console.log(a[property]);
}
// outputs f

但是,请注意,"own property"在javascript中具有特定的含义,因此强烈建议在遍历属性时检查属性是否是对象自己的属性(例如,忽略继承的属性)。

o = new Object();
o.prop = 'exists';
o.hasOwnProperty('prop');             // returns true
o.hasOwnProperty('toString');         // returns false
o.hasOwnProperty('hasOwnProperty');   // returns false