【问题标题】:hasOwnProperty in JavaScriptJavaScript 中的 hasOwnProperty
【发布时间】:2010-04-08 13:17:48
【问题描述】:

考虑:

function Shape() {
    this.name = "Generic";
    this.draw = function() {
        return "Drawing " + this.name + " Shape";
    };
}

function welcomeMessage()
{
    var shape1 = new Shape();
    //alert(shape1.draw());
    alert(shape1.hasOwnProperty(name));  // This is returning false
}

.welcomeMessage 调用了body.onload 事件。

我希望 shape1.hasOwnProperty(name) 返回 true,但它返回 false。

正确的行为是什么?

【问题讨论】:

标签: javascript


【解决方案1】:

hasOwnProperty 是一个接受字符串参数的普通 JavaScript 函数。

当您调用shape1.hasOwnProperty(name) 时,您将传递name 变量(不存在)的值,就像您编写alert(name) 时一样。

您需要使用包含name 的字符串调用hasOwnProperty,例如:shape1.hasOwnProperty("name")

【讨论】:

  • 不要忘记添加 hasOwnProperty() 返回一个布尔值,指示指定的属性(在本例中为名称)是否存在
【解决方案2】:

hasOwnProperty 期望属性名称为字符串,因此应为 shape1.hasOwnProperty("name")

【讨论】:

    【解决方案3】:

    试试这个:

    函数welcomeMessage() { var shape1 = new Shape(); //警报(shape1.draw()); 警报(shape1.hasOwnProperty(“名称”)); }

    在 JavaScript 中使用反射时,成员对象总是以字符串的形式引用。例如:

    for(i in obj) { ... }

    循环迭代器 i 将保存一个带有属性名称的字符串值。要在代码中使用它,您必须使用数组运算符来处理属性,如下所示:

    for(我在 obj 中){ alert("obj 的值。" + i + " = " + obj[i]); }

    【讨论】:

      【解决方案4】:

      hasOwnProperty() 是一个很好的属性来验证对象键。 示例:

      var obj = {a:1, b:2};
      
      obj.hasOwnProperty('a') // true
      

      【讨论】:

      • Re"nice property":不就是函数吗?
      猜你喜欢
      • 2023-03-12
      • 2021-01-07
      • 1970-01-01
      • 2014-12-15
      • 2012-03-12
      • 2019-01-30
      • 1970-01-01
      • 2011-08-15
      • 1970-01-01
      相关资源
      最近更新 更多