Javascript:何时在构造函数中定义函数以及何时使用原型(prototype)?

标签 javascript prototype

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

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

另一个是:

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

在什么情况下应该使用第一种构造,在什么情况下应该使用第二种构造?

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

提前致谢!

最佳答案

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

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

  • 包含特定值
  • 其他类型的特定功能(您可能每次都构建不同的功能)

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

来自MDN on objects :

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.

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

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

缺点是 Class 的每个实例都有不同的函数实例。这最常用于 modules。 (您只有一个实例)。就个人而言,我更喜欢完全按照 ThiefMaster 在评论中的建议去做:我在我的私有(private)函数前加上 _ :

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

关于Javascript:何时在构造函数中定义函数以及何时使用原型(prototype)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13359363/

相关文章:

javascript - 在 replace() 中调用 ajax 函数

javascript - 对字符串执行简单的数字测试

javascript - 对 js proto 和分配新属性感到困惑

c++ - arch_prtcl C++ 原型(prototype)

javascript - JS。原型(prototype)奇怪行为中的属性

javascript - 未捕获的类型错误 : Immutable prototype object '#<Object>' cannot have their prototype set

javascript - 自定义元素设置 : constructor vs connectedCallback

javascript - Gruntfile 中的 <%= %> 变量语法抛出 "unable to read"

javascript - 什么是javascript中的基础对象

javascript - 原型(prototype)是怎么回事