为什么eem . hasownproperty()为假?

Why elem.hasOwnProperty() is false

本文关键字:为假 eem hasownproperty 为什么      更新时间:2023-09-26

我有一个点击处理程序

e.addEventListener('click', this.Multiply, false);

和函数

this.Multiply = function () {
    APi.Multiply(this);
};

和简单的Select元素。
这里得到Select element

为什么要跑

this.selectedIndex 

给出value => 2

但是运行this.getOwnPropertyNames()会抛出错误

this.hasOwnProperty('selectedIndex') ->给出假?

这是因为selectedIndex实际上是HTMLSelectElement原型上的一个属性,而不是一个实例属性。要按照您的意愿进行测试,您可以尝试这样做:

this.__proto__.hasOwnProperty('selectedIndex');

this.constructor.prototype.hasOwnProperty('selectedIndex');

你应该得到你期望的结果。

当然,这假设您的this实例实际上是您选择的元素。当然有了这个HTML:

<select id="example"></select>

运行javascript:

var el = document.getElementById("example");
console.log(el.__proto__.hasOwnProperty('selectedIndex'));

将打印true到控制台