通过原型链继承的方法可以针对所有实例进行通用更改,例如:
function Class () {}Class.prototype.calc = function (a, b) { return a + b;}// Create 2 instances:var ins1 = new Class(), ins2 = new Class();// Test the calc method:console.log(ins1.calc(1,1), ins2.calc(1,1));// -> 2, 2// Change the prototype methodClass.prototype.calc = function () { var args = Array.prototype.slice.apply(arguments), res = 0, c; while (c = args.shift()) res += c; return res; }// Test the calc method:console.log(ins1.calc(1,1,1), ins2.calc(1,1,1));// -> 3, 3请注意如何更改应用于两个实例的方法?这是因为
ins1和
ins2共享相同的
calc()功能。为了使用在构造过程中创建的公共方法来执行此操作,您必须将新方法分配给已创建的每个实例,这是一项艰巨的任务。这是因为
ins1并且
ins2将具有自己的,单独创建的
calc()功能。
在构造函数内部创建方法的另一个副作用是性能较差。每次构造函数运行时,都必须创建每个方法。原型链上的方法创建一次,然后由每个实例“继承”。另一方面,公共方法可以访问“私有”变量,而继承方法是不可能的。
至于您的
function Class() {}vsvarClass=function(){}问题,在执行之前,前者已“提升”到当前作用域的顶部。对于后者,将悬挂变量声明,而不是赋值。例如:// Error, fn is called before the function is assigned!fn();var fn = function () { alert("test!"); }// Works as expected: the fn2 declaration is hoisted above the callfn2();function fn2() { alert("test!"); }


