javascript中的构造函数和原型

and*_*d-k 4 javascript

这两个代码有什么区别,我应该使用哪一个?

function Test() {}
Test.method = function() {};
Run Code Online (Sandbox Code Playgroud)

使用Prototype:

function Test() {}
Test.prototype.method = function() {};
Run Code Online (Sandbox Code Playgroud)

lea*_*eaf 5

第一种情况:静态方法.

function Test() {}
Test.method = function () { alert(1); };
var t = new Test;
Test.method(); // alerts "1"
t.method(); // TypeError: Object #<Test> has no method 'method'
Run Code Online (Sandbox Code Playgroud)

第二种情况:实例方法.

function Test() {}
Test.prototype.method = function () { alert(1); };
var t1 = new Test;
var t2 = new Test;
t1.method(); // alerts "1"
t2.method(); // alerts "1"
Test.method(); // TypeError: Object function Test() {} has no method 'method'
Run Code Online (Sandbox Code Playgroud)