[英]Correct syntax for setting object's property to return value of an object-function?
I'm learning javascript and was going through an example here: https://developer.mozilla.org/en/A_re-introduction_to_JavaScript 我正在学习javascript,并在此处浏览示例: https : //developer.mozilla.org/en/A_re-introduction_to_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;
}
var x = new Person('mickey', 'mouse');
document.write(x.fullName());
Why are the lines of code 为什么代码行
this.fullName = personFullName;
this.fullNameReversed = personFullNameReversed;
instead of 代替
this.fullName = personFullName();
this.fullNameReversed = personFullNameReversed();
I thought we're setting this.fullName
based on the return value of personFullName()
我以为我们根据
personFullName()
的返回值设置this.fullName
That code is making the "fullName" and "fullNameReversed" properties be functions , not simple properties. 该代码使“ fullName”和“ fullNameReversed”属性成为函数 ,而不是简单的属性。
Thus when you want the full name you'd write x.fullName();
因此,当您需要全名时,可以编写
x.fullName();
Functions are objects in JavaScript and can be the value of variables and properties. 函数是JavaScript中的对象,可以是变量和属性的值。 This is a feature that makes JavaScript surprisingly powerful.
此功能使JavaScript异常强大。
this.fullName = personFullName;
Creates a method called fullName
, and assigns it the function declared as personFullName
创建一个名为
fullName
的方法,并将该方法分配给声明为personFullName
的函数。
If you were to do 如果你要做
this.fullName = personFullName();
that would create an object property called fullName
that held the value that personFullName()
produced at that particular moment when invoked. 它将创建一个名为
fullName
的对象属性,该属性保存在调用的那个特定时刻personFullName()
产生的值。
personFullName
returns the function itself (like a pointer). personFullName
返回函数本身(如指针)。
personFullName()
returns the results of the function. personFullName()
返回函数的结果。
This allows the Person
object to have a method that returns the full name, as opposed to a property. 这允许
Person
对象具有返回全名而不是属性的方法。 If I use this object like x.first = newVal
, the fullName
method re-calculates the full name. 如果我使用
x.first = newVal
这样的对象, fullName
方法将重新计算全名。
If it were a property, I would have to use it like ''x.first = newVal; 如果它是一个属性,我将不得不像``x.first = newVal; x.fullName = newFullName;'.
x.fullName = newFullName;'。
Hope this helps. 希望这可以帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.