简体   繁体   English

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

[英]Javascript functions and objects using equal operator

I am trying to understand Javascript concepts from https://developer.mozilla.org/en-US/docs/JavaScript/A_re-introduction_to_JavaScript . 我正在尝试从https://developer.mozilla.org/zh-CN/docs/JavaScript/A_re-introduction_to_JavaScript理解Javascript概念。 Please see the code below; 请参见下面的代码;

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;
}

I am confused why function personFullName() is called like 我很困惑为什么函数personFullName()像

this.fullName = personFullName;

why it is not called like; 为什么不这样称呼;

this.fullName = personFullName();

And same for the below; 和下面的一样;

this.fullNameReversed = personFullNameReversed;

I know functions are objects in javascript but i am unable to understand this concept? 我知道函数是javascript中的对象,但我无法理解这个概念?

Because the Person object is assigning itself a method , not the results of a function. 因为Person对象是为其分配方法 ,而不是函数的结果。 That is the reason it doesn't call the function . 这就是它不调用该函数的原因。

This way you can do this. 这样您就可以做到这一点。

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