将函数放入对象并对其进行原型设计之间的区别?

时间:2011-09-12 02:17:31

标签: javascript

在对象中添加函数并将它们原型化到对象上有什么区别?

原型设计允许对象/模型自行调用吗?

2 个答案:

答案 0 :(得分:3)

“函数对象”通常用于“命名”一组函数,以便有一个容器对象具有多个方法而不是许多全局函数。好处是保持代码组件按对象(可能是对象层次结构)分类或分组,对性能没有任何好处,如果全局函数被精心命名,则应该没有合理的命名冲突机会。也就是说,主要目的是创建整齐的逻辑功能组。

通过“原型设计方法”,我认为你的意思是使用构造函数来创建实例。构造函数和原型用于需要继承的地方,它们是“命名空间”的完全不同的策略,使用一个并不排除另一个。使用原型进行继承并使用“函数对象”对实例(以及构造函数)进行分组是非常合理的。

答案 1 :(得分:1)

这是编码示例。

// when defining "Bla", the initial definition is copied into the "prototype"
var Bla = function()
{
    this.a = 1;
}
// we can either modify the "prototype" of "Bla"
Bla.prototype.b = 2;
// or we can modify the instance of "Bla"
Bla.c = 3;

// now lets experiment with this..

var x = new Bla();  // read: "clone the prototype of 'Bla' into variable 'x'"  
alert(x.b);     // alerts "2"
alert(x.c);     // undefined   -- because "c" doesn't exist in the prototype
alert(Bla.c);   // alerts "3"  -- "Bla" is an object, just like your instance 'x'

// also note this:
Bla.a = 1337;
var y = new Bla();
alert (y.a);    // alerts "1"  -- because the initial definition was cloned, 
                // opposed to the current state of object "Bla"