在构造函数中声明属性

Declaring a property inside a constructor function

本文关键字:属性 声明 构造函数      更新时间:2023-09-26

我强烈怀疑我通过运行下面列出的代码片段得到的错误是因为JavaScript不允许在构造函数内部声明属性,但我不能确定。

var Person = function(firstName, lastName)
{
  getName: function() {
    return this.firstName + ' ' + this.lastName;
  }
};
var person = new Person('Joe', 'Bloggs');
alert('Hello, ' + person.getName() + "!");
/*
Exception: SyntaxError: function statement requires a name
@Scratchpad/2:4
*/

请确认我的怀疑是否正确?如果是,那么添加属性的方法是:

  1. 是否使用对象字面语法?

    var Person = function(firstName, lastName)
    {
      this.firstName = firstName;
      this.lastName = lastName;
    };
    var person = { // object literal
      getName: function() {
        return this.firstName + " " + this.lastName;
      }
    };
    
  2. 或者将属性添加到构造函数的原型中?

    var Person = function(firstName, ..) { ... }
    Person.prototype.getName = ...;
    

我认为JavaScript处理这一行:

getName: function() {
    return this.firstName + ' ' + this.lastName;
  }

作为标记函数声明。您想要的可能是:

this.getName = function() {
    return this.firstName + ' ' + this.lastName;
  }

它的工作原理是这样的:

var Person = function(firstName, lastName) {
  this.firstName = firstName;
  this.lastName = lastName;
  this.getName = function() {
    return this.firstName + ' ' + this.lastName;
  }
};
var person = new Person('Joe', 'Bloggs');
alert('Hello, ' + person.getName() + "!");

但是正如前面提到的,你应该加入原型,这样新对象就可以共享一个方法。

Person.prototype.getName = function getName() { return this.firstName  " " + this.lastName;}

也许你可以去看看TypeScript。它可以正确地编译所有内容,并且您可以获得更简单的语法。然后你可以这样写:

class Person {
    constructor(private firstName: string, private lastName: string) {}
    public getName(): string {
        return this.firstName + " " + this.lastName;
    }
}

你也可以定义一个getter属性(setter也适用于set):

function Person(firstName, lastName) {
  this.firstName = firstName;
  this.lastName = lastName;
};
Object.defineProperty(Person.prototype, "name", {
    get : function () {
        return this.firstName + " " + this.lastName;
    }
});
var person = new Person('Joe', 'Bloggs');
alert('Hello, ' + person.name + "!");