Javascript oops:用原型定义函数或用原型定义函数(Javascript oops: defining function with or witout prototype)

编程入门 行业动态 更新时间:2024-10-26 14:34:40
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 () { }

更多推荐

本文发布于:2023-07-28 04:32:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1300393.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:原型   函数   定义   或用   oops

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!