在构造函数中声明属性
Declaring a property inside a constructor function
我强烈怀疑我通过运行下面列出的代码片段得到的错误是因为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 = ...;
我认为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 + "!");
相关文章:
- 获取HTML属性中CSS声明的值
- 如何在AngularJS工厂中正确声明对象属性
- 在样式表中声明元素后,删除该元素的悬停属性
- 在Aurelia computeds中,当设置依赖关系时,如何声明对对象属性的依赖关系
- 什么's;var'声明的变量和'这'在Javascript中创建了属性
- 如何区分未声明和未定义的 JavaScript 对象属性
- "无法读取属性'id'未定义的“;解析工厂中声明的数组时
- 无法使用typescript访问angular中另一个控制器中声明的$rootscope属性
- 属性初始值设定项在声明之前未定义
- 如何使用ES6在Ember中声明可观察性或计算属性
- 使用原型而不是在对象本身上声明属性有什么好处吗?
- 对象属性的分配顺序是否与声明顺序相同
- Javascript - 在变量声明中使用大括号将多个变量分配给对象属性
- 在 onClick 属性中声明变量,并在 onClick 中使用多个命令
- SCRIPT5039:重新声明常量属性 - IE 9 Javascript 问题
- Javascript 数组声明(可能误用长度属性?)
- 在 angularjs 控制器范围内声明函数和属性,但不附加到$scope
- ES7 类:在构造函数之外声明属性
- jQuery验证插件,用属性声明需要的规则不工作
- 具有开放端构造函数参数的参数属性声明