【发布时间】:2016-03-13 17:06:06
【问题描述】:
我想要做的如下:
var Person = function(name) {
this.name = name;
}
Person.prototype.getName = function () {
return this.name;
}
// This will return error;
console.log(Person('John').getName());
// While this won't.
var p1 = new Person('john');
console.log(p1.getName());
我是不是误会了什么?
【问题讨论】:
-
当您使用
new时,会创建一个实例,并且原型中定义的函数可用于对象 -
你为什么要避免使用
new? -
@mattBrowne 就是这样,我正在尝试摆脱 new 而不返回任何错误。我只是在尝试为新项目创建库时展示了一个小示例。
标签: javascript oop