【问题标题】:One object , two methods一个对象,两种方法
【发布时间】:2011-02-22 10:06:08
【问题描述】:

我试图理解为什么会这样

// .................................................. ..........

var hero = { 
  name: 'Joni', 
  type: 'blond',
  sayName: function() { 
    return this.name; 
  } 

  sayType: function() { 
    return this.type; } 
} 
document.write( hero.sayName()+ "</br>"); 
document.write( hero.sayType());

// .................................................. ..........

但这不起作用

// .................................................. ..........

var hero = { 
  name: 'Joni', 
  type: 'blond',
  sayName: function() { 
    return this.name; 
  } 

  sayType: function() { 
    return this.type; 
    } 
} 
document.write( hero.sayName()+ "</br>"); 
document.write( hero.sayType());

// .................................................. ..........

谢谢

【问题讨论】:

  • 什么不完全正确,两个代码块的区别在哪里?
  • 杀了我,但区别在哪里?
  • 由于缺少逗号,它不应该同时适用于两者。
  • 另外,sayName 属性后面少了一个逗号。
  • 请发布您的实际代码。这两个示例都包含错误,不应正常工作。

标签: javascript


【解决方案1】:

您在“var hero”语句的末尾缺少一个分号。您还缺少一些其他逗号。

var hero = { 
  name: 'Joni', 
  type: 'blond',
  sayName: function() { 
    return this.name; 
  }, // <<--- You missed the comma here

  sayType: function() { 
    return this.type; 
    } 
};  // <<--- You missed the semi colon!
document.write( hero.sayName()+ "</br>"); 
document.write( hero.sayType());

接下来,您只需通过 JSLINT 运行代码即可完全避免这些问题。转到 jslint.com,粘贴您的代码,您将看到答案。//

【讨论】:

  • 这种情况下不需要分号:stackoverflow.com/questions/42247/…
  • @aiham。它可能不是“必需的”,但您依赖于 javascript 的分号插入。如果你读过克劳福德的书,你会知道这是一件坏事,不能总是依赖。在我的团队中,你不能签到。
  • 我也不会这样做,但这不是导致错误的原因。
【解决方案2】:

不同之处在于第二块中saytype函数之前的enter。除了逗号,我看不出它为什么不起作用。

【讨论】:

    【解决方案3】:

    sayName 函数后缺少逗号。除了换行符(没有区别)之外,我看不出这两个代码块之间的区别。两个代码块都缺少这个逗号。

    var hero = { 
      name: 'Joni', 
      type: 'blond',
      sayName: function() { 
        return this.name; 
      },// <---  Missing Comma
    
      sayType: function() { 
        return this.type; 
        } 
    } 
    document.write( hero.sayName()+ "</br>"); 
    document.write( hero.sayType());
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-04-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多