質問

I was reading the re-introduction to JavaScript on MDN website and came across this in the Custom Objects section:

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

It says on the MDN website that you can make a reference to the personFullName() and personFullNameReversed() functions from within the Person constructor simply by typing in their names and assigning them as values to the two variables stated in the code above (this.fullName and this.fullNameReversed). This is all very clear to me, but my question is why are the brackets next to personFullName and personFullNameReversed omitted? Shouldn't it say:

this.fullName = personFullName();
this.fullNameReversed = personFullNameReversed();?

The way that it was presented in the example from the MDN website I feel like those fullName and fullNameReversed properties from the Person constructor are pointing to some already declared global variables instead of functions declared outside of the Person constructor.

役に立ちましたか?

解決

If you add the brackets, you'll call the functions and assign their return values to this.fullName and this.fullNameReversed.

The code is referring to the functions, not calling them.

他のヒント

It's assigning the function, not the result of the function. It's equivalent to:

function Person(first, last) {
    this.first = first;
    this.last = last;
    this.fullName = function () {
        return this.first + ' ' + this.last;
    };
    this.fullNameReversed = function () {
        return this.last + ', ' + this.first;
    };
}

so now you can do:

var jack = new Person('Jack', 'Smith');
console.log(jack.fullName()); // Jack Smith
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top