javascript - 如何在个人项目中使用此代码?它到底对你有什么作用

标签 javascript inheritance namespaces ecmascript-5

我的普通 js 代码的结构一直存在问题,涉及以下方面 局部/全局变量/方法、继承等

我搜索了一个很好的代码示例,发现了这个脚本:markerwithlabel.js

我对这一点很好奇:

/**
 * @param {Function} childCtor Child class.
 * @param {Function} parentCtor Parent class.
 * @private
 */
function inherits(childCtor, parentCtor) {
  /* @constructor */
  function tempCtor() {}
  tempCtor.prototype = parentCtor.prototype;
  childCtor.superClass_ = parentCtor.prototype;
  childCtor.prototype = new tempCtor();
  /* @override */
  childCtor.prototype.constructor = childCtor;
}

来源:https://github.com/googlemaps/v3-utility-library/blob/master/packages/markerwithlabel/src/markerwithlabel.js

如何在个人项目中使用此代码?它到底对你有什么作用。

显然这个片段被广泛使用: https://github.com/search?p=5&q=%22function+inherits%28childCtor%2C+parentCtor%29+%7B%22&type=Code

最佳答案

这是在 javascript 中执行继承的原型(prototype)方法。此函数 inherits(childCtor, ParentCtor) 只是将属性和功能从 parentCtor 传递到 childCtor。这是在相关对象之间共享功能的面向对象原则。这段代码的作用与 es2015 中的 extends 在对象中的作用完全相同。请参阅下面我的评论,我试图保持开放,而不是更多技术性。

function inherits(childCtor, parentCtor) 
{
  // This declares a function to be used as a constructor for childCtor
  function tempCtor() {}
      // This copies the prototype of the parent to the temporary class which is thechild, 
      // remember that the parent's prototype has properties that the child is inheriting
      tempCtor.prototype = parentCtor.prototype;
      // this adds a property called superClass inside child object that informs it who the parent is. so when you access that property it will refer to the parent
      childCtor.superClass_ = parentCtor.prototype;
      // This is where the new instance of child object is created through using tempCtor as the basis because all data was stored in it.
      childCtor.prototype = new tempCtor();

  // this then informs the childCtor that the method called constructor refers to itself
  childCtor.prototype.constructor = childCtor;
}

我只是想让它快一点,您可以阅读有关此主题的更多信息 here

关于javascript - 如何在个人项目中使用此代码?它到底对你有什么作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61093150/

相关文章:

javascript - ajax页面加载后重新初始化函数

javascript - AngularJS ui-router 到一个状态但使用不同的 URL

c++ - 错误 : Invalid use of incomplete type

php - 使用变量名获取常量值

javascript - 如何处理查询中的数组值?

javascript - 不要将 Indesign 标签添加到根元素?

Delphi接口(interface)继承: Why can't I access ancestor interface's members?

c# - 具有强类型返回类型的抽象方法

c++ - 如何从另一个命名空间中显式特化函数模板?

namespaces - 将 TYPO3 V 6.1 中的外部库用于扩展