【问题标题】:Javascript functions and objects using equal operator使用相等运算符的 Javascript 函数和对象
【发布时间】:2013-01-28 15:08:09
【问题描述】:

我正在尝试从 https://developer.mozilla.org/en-US/docs/JavaScript/A_re-introduction_to_JavaScript 理解 Javascript 概念。 请看下面的代码;

function personFullName() {
  return this.first + ' ' + this.last;
}

function personFullNameReversed() {
  return this.last + ', ' + this.first; 
}

function Person(first, last) {
  this.first = first;
  this.last = last;
  this.fullName = personFullName;
  this.fullNameReversed = personFullNameReversed;
}

我很困惑为什么函数 personFullName() 被称为

this.fullName = personFullName;

为什么不叫like;

this.fullName = personFullName();

下面也一样;

this.fullNameReversed = personFullNameReversed;

我知道函数是 javascript 中的对象,但我无法理解这个概念?

【问题讨论】:

    标签: javascript function object equals operator-keyword


    【解决方案1】:

    因为Person 对象为自己分配了一个方法,而不是函数的结果。这就是它不调用函数的原因。

    这样你就可以做到了。

    var p = new Person("Matt", "M");
    p.fullName(); // Returns "Matt M"
    p.fullNameReversed(); // Returns "M, Matt"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-03-31
      • 1970-01-01
      • 2011-01-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多