我一直在我的香草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/search?p=5&q=%22function+inherits%28childCtor%2C+parentCtor%29+%7B%22&type=Code
这是在javascript中执行继承的原型方法。这是在相关对象之间共享功能的面向对象原则。此代码与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