Javascript:何时在构造函数中定义函数以及何时使用原型? [英] Javascript: when to define functions inside constructor and when to use prototype?

查看:111
本文介绍了Javascript:何时在构造函数中定义函数以及何时使用原型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习Javascript并且有几个关于Javascript和OOP的问题。我已经注意到各种教程中类中函数的不同声明。首先是内部构造函数:

I'm learning Javascript and have several questions concerning Javascript and OOP. I've noticed different declarations of functions in "classes" in various tutorials. First is the inside constructor:

Class = function () {
  this.doSomething = function() {....};
}

另一个是:

Class = function () {}
Class.prototype.doSomething  = function() {....};

在哪种情况下应该使用第一种结构,在哪种情况下应该使用第二种结构?

In which situations should the first construction be used, and in which situation should the second construction be used?

另一个问题是:我是否正确理解js中没有 protected 属性或方法?改为使用什么?

And the other question is: have I understood correctly that there's no protected properties or methods in js? What is to be used instead?

提前谢谢!

推荐答案

当您在构造函数中将函数定义为 this.myFunction = ... 时,它特定于您的实例。这意味着必须为所有实例构建并保存它,这可能很重。它也不能被继承。

When you define a function inside the constructor as this.myFunction=..., it is specific to your instance. This means that it must be constructed and kept in memory for all instances, which may be heavy. It also can't be inherited .

这样做的唯一正当理由是:

The only valid reason to do this are :


  • 包含特定值

  • 其他类型的特定函数(每次可以构建不同的函数)

大多数情况下,您真正​​需要的是在原型上定义的函数。

Most often, what you really need is a function defined on the prototype.

来自对象上的MDN


JavaScript中的所有对象都来自Object;所有对象
都从Object.prototype继承方法和属性,尽管它们可以覆盖
。例如,其他构造函数的原型
覆盖构造函数属性并提供自己的toString
方法。对Object原型对象的更改将传播到所有
对象,除非这些更改的属性和方法是沿原型链进一步覆盖

All objects in JavaScript are descended from Object; all objects inherit methods and properties from Object.prototype, although they may be overridden. For example, other constructors' prototypes override the constructor property and provide their own toString methods. Changes to the Object prototype object are propagated to all objects unless the properties and methods subject to those changes are overridden further along the prototype chain.

关于您的其他问题:以下代码构建了一个不可直接访问的函数:

Regarding your additional question : the following code builds a non directly accessible function :

Class = function () {
   var imprivate = function(){...};
   this.doSomething = function() { uses imprivate};
}

缺点是每个<$的实例都有不同的函数实例C $ C>类。这通常用于模块(您只有一个实例)。就个人而言,我更喜欢完全按照ThiefMaster的建议做评论:我的私人函数前缀为 _

A downside is that you have a different function instance for each instance of Class. This is most often done for modules (from which you have only one instance). Personally, I prefer to do exactly as suggested by ThiefMaster in comment : I prefix my private functions with _ :

// private method
XBasedGrapher.prototype._ensureInit = function() {

这篇关于Javascript:何时在构造函数中定义函数以及何时使用原型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆