是否可以在不使用原型的情况下向函数添加属性?我知道使用原型您可以执行以下操作:
function Gadget(name, color) {
this.name = name;
this.color = color;
this.whatAreYou = function(){
return 'I am a ' + this.color + ' ' + this.name;
}
}
没有原型对象,是否可以实现相同的目标?
您的要求有点混乱。您目前没有为方法或属性使用原型(无法从问题中得知您是否意识到了这一点),并且如果您使用如下方法从函数中创建对象,则该技术可以正常工作new
:
function Gadget(name, color) {
this.name = name;
this.color = color;
this.whatAreYou = function(){
return 'I am a ' + this.color + ' ' + this.name;
}
}
var x = new Gadget("Faucet", "red");
x.whatAreYou(); // returns 'I am a red Faucet'
工作演示:http : //jsfiddle.net/jfriend00/wPP7N/
使用new
运算符时,它将创建一个新对象并调用this
分配给该新对象的函数。您添加到对象中this
指向构造函数的所有属性都将成为新对象的属性。
事实上,像一个动态值的属性name
,并color
在你的例子经常这样分配的构造函数有一点优势,使用的原型,因为他们会被分配一个动态值。whatAreYou
使用原型分配诸如您的方法之类的方法具有性能优势,因为在构造函数时只需运行较少的代码-尽管相差不大。
为了进行比较和对比,使用原型定义该方法的代码如下所示:
function Gadget(name, color) {
this.name = name;
this.color = color;
}
Gadget.prototype.whatAreYou = function(){
return 'I am a ' + this.color + ' ' + this.name;
}
var x = new Gadget("Faucet", "red");
x.whatAreYou(); // returns 'I am a red Faucet'
如果只是简单地调用该函数,例如:
Gadget();
然后,不会创建新对象,并且this
将指向全局对象或将其指向undefined
(在严格模式下),因此这些属性将不在特定于Gadget的对象上。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句