下面是我的类(class):
function myfunc(){
// some code
}
1) 声明类的方法/函数
myfunc.getInstance = function(){
// some code
};
或者我可以像下面这样定义:
myfunc.prototype.getInstance = function(){
// some code
};
请告诉我定义带有或不带有原型(prototype)的方法/函数有什么区别。
最佳答案
与
myfunc.prototype.getInstance = 函数(){
//一些代码
};
如果你创建任何继承myfunc的对象,它将能够通过原型(prototype)链访问getInstance方法。新对象的 __ proto __ 将指向其父对象的原型(prototype),即 myfunc 的
与
myfunc.getInstance = function(){
// some code};
getInstance 方法不能被继承,因此只有 myfunc 能够调用它,继承它的对象不能调用它。
示例
function myfunc(){
}
myfunc.getInstance = function(){
console.log("I can be invoked only by myfunc")
}
myfunc.prototype.getInstance2 = function(){
console.log("I can be inherited and called by other objects too")
}
let newobj = new myfunc();
newobj.getInstance2();
// I can be inherited and called by other objects too
newobj.getInstance();
// Uncaught TypeError: newobj.getInstance is not a function
myfunc.getInstance();
// I can be invoked only by myfunc
关于JavaScript 哎呀 : defining function with or witout prototype,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15674766/