我强烈怀疑通过运行下面列出的代码片段得到的错误是因为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
*/
请问您确认我的怀疑是否正确?如果是,那么添加属性的方法是:
要么使用对象文字语法?
var Person = function(firstName, lastName)
{
this.firstName = firstName;
this.lastName = lastName;
};
var person = { // object literal
getName: function() {
return this.firstName + " " + this.lastName;
}
};
或者,要将属性添加到构造函数的原型?
var Person = function(firstName, ..) { ... }
Person.prototype.getName = ...;
答案 0 :(得分:2)
我认为JavaScript
对待这一行:
getName: function() {
return this.firstName + ' ' + this.lastName;
}
为labeled function declarations。你想要的可能就是:
this.getName = function() {
return this.firstName + ' ' + this.lastName;
}
答案 1 :(得分:1)
它会像这样工作:
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 + "!");