我的普通 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 中执行继承的原型(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/