这两个代码有什么区别,我应该使用哪一个?
function Test() {}
Test.method = function() {};
带有原型(prototype):
function Test() {}
Test.prototype.method = function() {};
最佳答案
第一种情况:静态方法。
function Test() {}
Test.method = function () { alert(1); };
var t = new Test;
Test.method(); // alerts "1"
t.method(); // TypeError: Object #<Test> has no method 'method'
第二种情况:实例方法。
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'
关于javascript - javascript中的构造函数和原型(prototype),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21737929/