继承和模块模式
Inheritance and module pattern
我正试图通过以下方式实现模块模式的继承:
Parent = function () {
//constructor
(function construct () {
console.log("Parent");
})();
// public functions
return this.prototype = {
test: function () {
console.log("test parent");
},
test2: function () {
console.log("test2 parent");
}
};
};
Child = function () {
// constructor
(function () {
console.log("Child");
Parent.call(this, arguments);
this.prototype = Object.create(Parent.prototype);
})();
// public functions
return this.prototype = {
test: function()
{
console.log("test Child");
}
}
};
但我不能从孩子的实例调用test2()
。
var c = new Child();
c.test2(); // c.test2 is not a function
我错了什么?
您没有以正确的方式使用模块模式。不知怎的,您的"构造函数"被调用为一个立即调用的函数表达式(IIFE(,而模块闭包不是。应该是反过来。
此外,不能指定给this.prototype
。要创建所有实例都将继承的原型对象,您需要将其分配给构造函数的prototype
属性(在您的情况下,this
关键字甚至指向全局window
对象(。
一旦有了它,就应该从IIFE返回构造函数,而不是原型对象
Parent = (function () {
// constructor
function construct () {
console.log("Parent");
};
// public functions
construct.prototype.test = function () {
console.log("test parent");
};
construct.prototype.test2 = function () {
console.log("test2 parent");
};
return construct;
})();
Child = (function () {
// constructor
function construct() {
console.log("Child");
Parent.apply(this, arguments);
}
// make the prototype object inherit from the Parent's one
construct.prototype = Object.create(Parent.prototype);
// public functions
construct.prototype.test = function() {
console.log("test Child");
};
return construct;
})();
(function () {
console.log("Child");
Parent.call(this, arguments);
this.prototype = Object.create(Parent.prototype);
})();
this
指的是window
,因为您将代码封装到了一个函数中。删除包装函数或将this
作为参数传递。
相关文章:
- Javascript,访问一个主要对象模块模式中的每个对象
- 模块模式和这个
- 显示模块模式在Knockout中设置模型的新实例
- Javascript中的模块模式和揭示模块模式是否仅在创建API时有用;s
- 用于多个选项卡和模块化的knockoutjs设计模式
- JavaScript模块模式-如何在使用对象/函数之前激发构造函数/init函数
- TypeScript代码类似于揭示模块模式结构
- 为什么在javascript中的模块模式中实现Lazy函数时范围会发生变化
- JavaScript:模块模式差异
- 显示模块模式中的私有成员
- 如何将window.setTimeout与javascript和模块模式一起使用
- j查询模块模式未命名 |如何访问“$”
- 挖空和显示模块模式的数据绑定问题
- 传递参数时如何避免模块模式中的 getter/setter 函数
- 将变量传递给 Javascript 模块化模式方法
- JavaScript 模块模式给出了意想不到的结果
- 从模块模式开始
- 试图通过模块模式在DOM元素上实现change()事件
- 揭示模块模式、KnockoutJS和CoffeeScript
- JavaScript 设计模式:模块模式和揭示模块模式之间的区别