定义JavaScript'类'的方法之间的区别

时间:2012-09-05 15:11:43

标签: javascript prototype function-prototypes

这两种在JavaScript中定义“类”的方法有什么区别?

方法一

在构造函数中定义方法:

function MyClass()
{
    this.foo = function() { console.log('hello world!'); };
}

方法二

在原型上定义方法:

function MyClass()
{}

MyClass.prototype.foo = function() { console.log('hello world!'); };

2 个答案:

答案 0 :(得分:4)

第一个将在对象的每个实例化上创建一个新的函数对象,第二个将为每个实例分配一个原型方法的引用。简而言之:第二个更有效,因为所有实例都将共享一个函数对象。

这只是原型链的逻辑,您可以尝试并通过任何对象访问任何内容:

var objLiteral = {foo:'bar'};

访问objLiteral.foo时,JS将首先查看对象本身已定义的属性,如果找到则返回值。如果JS无法在对象本身上找到属性,它将检查对象的原型,因此:

objLiteral.valueOf();//method defined @Object.prototype
objLiteral.valueOf === Object.prototype.valueOf //true

但是当你使用第一种方法时:

function SomeConstructor()
{
    this.methd = function()
    {
        return true;
    }
}
var f = new SomeConstructor();
var g = new SomeConstructor();
f.methd === g.methd;//FALSE!

这表明我们正在处理2个独立的函数对象。将函数定义移动到原型,f.methd === g.methd;将为真:

function SomeConstructor()
{
}
SomeConstructor.prototype.methd = function()
{
    return true;
}
var f = new SomeConstructor();
var g = new SomeConstructor();
f.methd === g.methd;//true!

回应你的评论:

在原型级别定义方法允许您更改特定任务的方法,然后“重置”将其恢复为默认行为。假设您正在创建一个AJAX请求的函数中:

someObject.toString = function(){ return JSON.stringify(this);}
//when concatinating this object you'll get its json string
//do a lot of stuff
delete (someObject.toString);

再次,JS将检查对象是否具有自己定义的本身的<{1}}属性。因此JS将删除您分配给toString属性的函数。下次调用toString时,JS将重新开始扫描原型链,并使用方法的第一次出现(在原型中)。让我们澄清一下:

toString

甚至更好,您甚至可以通过另一个原型的方法替换实例的方法:

function SomeConstructor()
{
}
SomeConstructor.prototype.methd = function()
{
    return true;
}
var f = new SomeConstructor();
var g = new SomeConstructor();
f.methd = function(){return false;};
g.methd();//returns true, still <-- method is gotten from the prototype
f.methd();//returns false <-- method is defined @ instance level
delete (f.methd);
f.methd();//returns true, f doesn't have the method, but the prototype still does, so JS uses that.

最后一个例子没有意义,因为f已经有f.methd = Object.prototype.valueOf;//for as long as you need 方法:它的继承链如下所示:valueOf,让你可以访问所有的Object.prototype方法!整洁,不是吗?

这些只是虚拟示例,但我希望您看到这是使JS非常灵活(有时过于灵活,我必须承认)和富有表现力的语言的功能之一。

答案 1 :(得分:2)

在第一种情况下,将为每个实例创建函数,并将其设置为对象中的foo属性。在第二种情况下,它是共享功能。当你调用obj.prop然后它在对象本身中查找它时,如果它不存在,那么它在proto对象中查找它,依此类推,它被称为chain of prototypes

例如,此代码提供foo

function MyClass() {
  this.foo = function () {};
}

var myVariable = new MyClass();
for (var i in myVariable) if (myVariable.hasOwnProperty(i)) console.log(i);

但这不是:

function MyClass() {
}

MyClass.prototype.foo = function () {};

var myVariable = new MyClass();
for (var i in myVariable) if (myVariable.hasOwnProperty(i)) console.log(i);
相关问题