在不使用原型的情况下向函数添加属性

Add properties to function without using prototype

本文关键字:函数 添加 属性 情况下 原型      更新时间:2023-09-26

是否可以在不使用原型的情况下向函数添加属性?我知道使用原型您可以执行以下操作:

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指向的对象的任何属性都将成为新对象的属性。

事实上,示例中具有动态值(如 namecolor)的属性通常在构造函数中像这样分配,因为为它们使用原型没有什么好处,因为它们被分配了一个动态值。 使用原型分配方法(如 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(在严格模式下),因此属性不会位于特定于小工具的对象上。

请参阅对您的问题的评论(您实际上并没有使用原型),但只是为了帮助您理解,使用原型将如下所示:

function Gadget(name, color) {
  this.name = name; 
  this.color = color; 
}
Gadget.prototype.whatAreYou = function(){
  return 'I am a ' + this.color + ' ' + this.name; 
}