Creating functions for an object in javascript

As far as I can tell, there are two main ways of creating functions for an object in javascript. They are: Method A, make it in the constructor: function MyObject() { this.myFunc1 = function() { ... } this.myFunc2 = function() { ... } ... } Method B, add it to the prototype: function MyObject() { ... } MyObject.prototype.myFunc1 = function() { ... } MyObject.prototype.myFunc2 = function() { .... } Obviously if you did: MyObject.myFunc3 = function() { .... } then `myFunc3` would become associated with MyObject itself, and not any new objects created with the `new` keyword. For clarity, we'll call it method C, even though it doesn't work for creating new objects with the `new` keyword. So, I would like to know what the differences between the two are. As far as I can tell they have the same effect logically, even if what's happening on the machine is different. If I were to guess I would say that the only real difference is when you're defining them in the constructor like in method A, it creates a whole new function object for each object that's created, and Method B only keeps one copy of it (in MyObject), that it refers to any time it's called. if this is the case, why would you do it one way over the other. Otherwise, what is the difference between method A and method B.
You can also create functions in objects like this

以上就是Creating functions for an object in javascript的详细内容,更多请关注web前端其它相关文章!

赞(0) 打赏
未经允许不得转载:web前端首页 » JavaScript 答疑

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址

前端开发相关广告投放 更专业 更精准

联系我们

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏