1

下面是我的课:

function myfunc(){
    // some code
}

1) 声明一个类的方法/函数

myfunc.getInstance = function(){
          // some code
};

或者,我可以定义如下:

myfunc.prototype.getInstance = function(){
    // some code
};

请告诉我使用或不使用原型定义方法/函数有什么区别。

4

2 回答 2

1

myfunc.prototype.getInstance = function(){ // some code };

如果您创建任何继承 myfunc 的对象,它将能够使用原型链访问 getInstance 方法。新对象的 __ proto __ 将指向其父对象的原型,即 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
于 2019-11-11T13:53:23.170 回答
0

原型函数旨在在类的对象上调用(就像 OOP 中的普通类)。可以直接在类上调用普通函数(如 OOP 中的静态类)。

function Foo ()
{
}

//Should be called through Foo.SayHello()
Foo.SayHello = function ()
{

}


/*
Should be called on the object of Foo
var MyObject = new Foo();
MyObject.SayHello();
*/

Foo.prototype.SayHello = function ()
{
}
于 2013-03-28T05:25:55.630 回答