为什么我需要为扩展函数设置构造函数
Why do I need to set constructor for a extend function?
我正试图完全理解"extend"在javascript中的工作原理。
这是我在谷歌上找到的一个简单的扩展函数
function extend(child, parent) {
var f = function() {}
f.prototype = parent.prototype;
var i;
for( i in parent.prototype ) {
child.prototype[i] = parent.prototype[i];
}
child.prototype.constructor = child;
child.parent = parent;
}
它有效,但我不理解"child.prototype.constructor=child"部分。没有它,该功能仍然有效。
这条线的用途是什么?
否。你在哪里找到的?它混合了两种方法:
经典原型的继承
function inherit(child, parent) {
var f = function() {}
f.prototype = parent.prototype;
child.prototype = new f();
child.prototype.constructor = child;
}
此函数创建一个新对象,该对象直接继承自parent
函数的原型对象。它是Object.create()
的旧式同义词。这样,就建立了一个原型链——child
的所有实例也继承自parent.prototype
。因为生成了一个新对象来覆盖child.prototype
,所以需要更新"constructor"属性。
mixin继承
这个函数只是在父对象原型对象的所有属性上循环,并将它们复制到子对象原型对象上。这正是公共辅助函数extend
所做的。它不会重置子函数的"prototype"属性,但也不会设置继承链。
function extend(child, parent) {
for (var i in parent.prototype ) {
child.prototype[i] = parent.prototype[i];
}
}
你是对的,线
child.prototype.constructor = child;
在这里是非常无用的-"构造函数"属性是不可枚举的,并且不会受到extend
的影响。
此外,您的函数将子函数对象的"父"属性设置为父函数,这是不需要的:
child.parent = parent;
在我看来,"child.protype.constructor"是该对象的基本/普通实现,它允许其他对象在不继承同一父对象的情况下从中扩展。因此,它是在"child.parent=parent"之前声明的。
这可能不能直接回答您的问题,但我想建议您使用John Resig:的extend
实现
- 简单JavaScript继承
它允许您创建一个名为init
的构造函数,如下所示:
var MyClass = Class.extend({
init: function() {
console.log("Running a constructor");
}
});
并安装这样的对象(正常):
var obj = new MyClass();
这个例子展示了如何在javascript 中继承类
var a = function(){
// class a constructor
this.a_priviligiate_var = 1;
}
a.prototype.a_public_var = 2;
var b = function(){
// class b constructor
// super call of class a constructor
// this line makes b class to inherit all privileged vars
b.prototype.constructor.call(this)
this.b_priviligiate_var = 3;
}
b.prototype.b_public_var = 4;
b.prototype = new a();
var c = new b();
定义索赔:
var a = function(){
// class a constructor
this.a_priviligiate_var = 1;
}
a.prototype.a_public_var = 2;
定义另一个类:
var b = function(){
// class b constructor
// super call of class a constructor
// this line makes b class to inherit all privileged vars
b.prototype.constructor.call(this)
this.b_priviligiate_var = 3;
}
b.prototype.b_public_var = 4;
正在设置超级(父)类。这条线复制了所有b.prototype
b.prototype = new a();
创建c 的实例
var c = new b();
- 如何从onclick函数设置全局变量并将其传递给另一个JS文件
- 使用JAVASCRIPT转换货币.可以't通过我的函数设置转换后的输入文本字段的值
- 将OnClick函数设置为<ul>,最后一个ul是擦除第一个ul-s
- 为什么我需要为扩展函数设置构造函数
- 使用命名函数设置多个事件响应
- 如何通过回调函数设置值
- 为模式设置的值在通过 AJAX 成功函数设置时不显示
- 如何停止一个函数并将其他函数设置为在 html5 的 javascript 中加载时运行
- 如何为JavaScript函数设置变量以嵌入视频
- 使用jquery每个函数设置最大计数
- angularjs如何为函数设置观察程序
- Javascript:为作为参数传递的函数设置参数
- 函数设置为允许的范围是什么
- 在 javascript 中从函数设置对象的值,而无需调用该函数
- 如何使用 javascript 函数设置 href 参数值
- 函数/设置间隔意外记录两次到控制台
- 我在输入字段上触发绑定时将函数设置为未定义
- CKEDITOR函数+设置
- 如何将点击函数设置为多个元素
- 在 Backbone 中将函数设置为属性.js给了我一个错误,但如果我在初始化方法中设置它,它会起作用