Javascript 如何在个人项目中使用此代码?这对你有什么好处

Javascript 如何在个人项目中使用此代码?这对你有什么好处,javascript,inheritance,namespaces,ecmascript-5,Javascript,Inheritance,Namespaces,Ecmascript 5,我一直对我的香草js代码的结构有问题,关于 局部/全局变量/方法、继承等 我在搜索一个好的代码示例时发现了以下脚本:markerwithlabel.js 我对这一点很好奇: /** * @param {Function} childCtor Child class. * @param {Function} parentCtor Parent class. * @private */ function inherits(childCtor, parentCtor) { /* @cons

我一直对我的香草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;
}
资料来源:

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

显然,这段代码被广泛使用:

这是在javascript中执行继承的原型方式。此函数
继承(childCtor,parentCtor)
只是将属性和功能从
parentCtor
传递到
childCtor
。这是一个面向对象的原则,在相关对象之间共享特性。此代码的作用与es2015中的
扩展
在对象中的作用完全相同。请参考我下面的评论,我试着开放,而不是更多的技术

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;
}

我只是想让它快一点,你可以进一步阅读关于这个主题的更多内容

这是否回答了你的问题?MDN的文章令人惊叹,我很高兴它起了作用。Javascript是一种很棒的语言。