简体   繁体   中英

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

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()

That code is making the "fullName" and "fullNameReversed" properties be functions , not simple properties.

Thus when you want the full name you'd write x.fullName();

Functions are objects in JavaScript and can be the value of variables and properties. This is a feature that makes JavaScript surprisingly powerful.

this.fullName = personFullName;  

Creates a method called fullName , and assigns it the function declared as 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.

personFullName returns the function itself (like a pointer).

personFullName() returns the results of the function.

This allows the Person object to have a method that returns the full name, as opposed to a property. If I use this object like x.first = newVal , the fullName method re-calculates the full name.

If it were a property, I would have to use it like ''x.first = newVal; x.fullName = newFullName;'.

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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