Javascript oops:用原型定义函数或用原型定义函数(Javascript oops: defining function with or witout prototype)
以下是我的课程:
function myfunc(){ // some code }1)声明类的方法/功能
myfunc.getInstance = function(){ // some code };或者我可以定义如下:
myfunc.prototype.getInstance = function(){ // some code };请告诉我使用或不使用原型定义方法/功能有什么区别。
Below is my class:
function myfunc(){ // some code }1) declaring a method/function of a class
myfunc.getInstance = function(){ // some code };Or alternatively i can define like below:
myfunc.prototype.getInstance = function(){ // some code };Please tell me what is the difference between defining method/function with or without prototype.
最满意答案
原型函数意味着在类的对象上调用(就像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 () { }Prototype functions are meant to be called on an object of class (like a normal class in OOPs). Where as normal functions can be called directly on the class (like a static class in OOPs).
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 () { }更多推荐
发布评论