【发布时间】:2019-05-03 22:44:39
【问题描述】:
hasOwnProperty 的行为似乎有所不同,具体取决于它是在构造函数还是实例上调用,具体取决于对包含的成员使用 this 或 let。
function Animal(_name) {
let name = _name;
this.getName = function() {
return name;
}
};
function Animal2(_name) {
this.name = _name;
let getName = function() {
return name;
}
}
let a = new Animal("greg");
let a2 = new Animal2("tim");
console.log(a.hasOwnProperty("name"));
console.log(a2.hasOwnProperty("name"));
console.log(Animal.hasOwnProperty("name"));
console.log(Animal2.hasOwnProperty("name"));
console.log("");
console.log(a.hasOwnProperty("getName"));
console.log(a2.hasOwnProperty("getName"));
console.log(Animal.hasOwnProperty("getName"));
console.log(Animal2.hasOwnProperty("getName"));
这会输出以下内容:
false
true
true
true
true
false
false
false
为什么会这样?我了解在构造函数中使用“let”模拟“私有”成员,这可以解释为什么 a.hasOwnProperty("name") 和 a2.hasOwnProperty("getName") 都返回 false,但不知道为什么构造函数不要“拥有”他们的方法。
【问题讨论】:
-
您在这里使用属性
name有点污染了您自己的研究,这些功能一直都有:(function test() {}).name是“测试”,@987654325 @ 是 ””。如果我们在 var 中捕获它们(例如var f = function...),那么在第一种情况下,名称仍然是“test”,而在第二种情况下,现在是您使用的 var 的名称。真正的问题是:为什么在 2019 年使用 hasOwnProperty,因为类是一回事,我们不再需要从函数中构建对象? -
你错了,Let 不是'私人成员',它只是一个 局部变量 。 javascript中没有私有元素,可能是下一个JS版本,但目前没有
-
@Mike'Pomax'Kamermans 是的,我可能应该检查一下 Animal.name 属性实际上是什么,哈哈。使用 hasOwnProperty 有什么替代方法?我没有意识到它已经过时了。是的,我知道类,我只是随意决定使用构造函数。但我想从现在开始我会使用类语法:)
-
'emulate' 也是错误的。 JavaScript 是一种基于原型的基于对象的语言,而不是基于类的语言。一切都不等价。
-
hasOwnProperty 不会过时,无论是今天还是明天。
标签: javascript function object ecmascript-6 hasownproperty