javascript - javascript 中的 "OWN"属性是什么

标签 javascript oop properties

这里我有一段代码,它使用 getter 和 setter 来定义和获取属性值。我使用对象构造函数创建了一个对象。我在 for...in 循环中传递了该对象。还使用了 getOwnPropertyNames() 方法对象。这是结果

"fullName" property is accessible in for...in loop

"fullName" is not visible in getOwnPropertyNames() method.That means it is

not a own property

这里我有两个基本问题。什么是自有属性(property)?如果“fullName”不是自有属性(property),那么它是什么类型的属性(property)?

function Name(first, last) {
    this.first = first;
    this.last = last;
}

Name.prototype = {
    get fullName() {
        return this.first + " " + this.last;
    },

    set fullName(name) {
        var names = name.split(" ");
        this.first = names[0];
        this.last = names[1];
    }
};
var obj=new Name('al','zami');
for(var i in obj){
   console.log(i); // fullName is here
}
console.log(Object.getOwnPropertyNames(obj)); // fullName is not here

最佳答案

hasOwnPropertygetOwnPropertyNames 是指直接分配给对象的属性,而不是只能通过对象的原型(prototype)链访问的属性。 this.foo =bar.foo = 算作自己的属性,因为您正在分配给实例。

“自有属性”在 section 4.3.30 中定义规范为:

property that is directly contained by its object

与“继承属性”相比,定义 ( 4.3.31) 为:

property of an object that is not an own property but is a property (either own or inherited) of the object’s prototype

也就是说,“自己的”属性在实例上,而不是原型(prototype)上。

最大的影响是原型(prototype)类(具有某些方法和/或静态属性的构造函数)。在经典的 OO 术语中,getOwnPropertyNames 将跳过类方法和任何具有 static 关键字的方法。

如果你看一下section 8.12.1在规范中,它间接排除了原型(prototype)。在步骤#3 中,运行时检查对象自身的属性以获取适当的属性名称。然而,在 section 8.12.2 (指的是没有“自己”限定符的 getProperty),步骤 #3-4 描述了在对象本身未找到属性时检查对象的原型(prototype)。

关于javascript - javascript 中的 "OWN"属性是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36456326/

相关文章:

javascript - 在 CSS 类中为图像赋值

c# regex - 从类文件 (.cs) 中选择类属性名称、方法名称和字段

javascript - window.print() 在 IE\Firefox 中不显示相同的打印屏幕 HTML

javascript - 在Modal中输出MySQL数据

javascript - 找到出现在两个数组中的两个元素并将它们放入另一个数组中

python - 在两个相关类中使用继承的最佳方式是什么

javascript - 返回第一个找到的值对象

c++ - 玩家移动时,GameBoy Advance对象未显示在正确的位置

matlab - 在 matlab 中扩展向量类

java - 从属性文件中删除键和值?