繁体   English   中英

使用相等运算符的Javascript函数和对象

[英]Javascript functions and objects using equal operator

我正在尝试从https://developer.mozilla.org/zh-CN/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;

为什么不这样称呼;

this.fullName = personFullName();

和下面的一样;

this.fullNameReversed = personFullNameReversed;

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

因为Person对象是为其分配方法 ,而不是函数的结果。 这就是它不调用该函数的原因。

这样您就可以做到这一点。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM