【发布时间】:2014-01-24 21:33:39
【问题描述】:
当父类永远不知道它有哪些子类时,我正在尝试找出一种子类访问父类的方法?
我正在使用 Object.create 创建我的类,现在我正在这样做。注意子类中的“obj.parent = parentClass”
必须有更好的方法来做到这一点,但我不知道。
var parentClass = (function() {
var obj = Object.create({});
var _parentProperty = 'foo';
Object.defineProperties(obj,
{
'parentProperty': {
configurable: false,
enumerable: true,
set: function(value) {
_parentProperty = value;
},
get: function() {
return _parentProperty;
}
},
'parentMethod': {
value: function() {
alert('Parent method called');
},
writable: false,
configurable: false,
enumerable: false
}
}
);
return obj;
})();
var childClass = (function() {
var obj = Object.create(parentClass);
obj.parent = parentClass;
var _childProperty = 'bar';
Object.defineProperties(obj,
{
'childProperty': {
configurable: false,
enumerable: true,
set: function(value) {
_childProperty = value;
},
get: function() {
return _childProperty;
}
},
'childMethod': {
value: function() {
alert('Child method called');
},
writable: false,
configurable: false,
enumerable: false
},
'callParent': {
value: function() {
alert(this.parent.parentProperty);
this.parent.parentMethod();
},
writable: false,
configurable: false,
enumerable: false
}
}
);
return obj;
});
var myClass = new childClass();
myClass.callParent();
【问题讨论】:
-
谢谢,读了一篇有趣的书,我将从那里尝试一些东西,但我没有使用 John Resig 的 Javascript 继承。
-
我发现我可以用
obj.parent = obj.__proto__;替换obj.parent = parentClass;,但这实际上并没有什么用处。我正在寻找要写入父类的内容,以便在子类中设置父类。 -
@thefourtheye 好点。我现在想知道那是不是 chrome 的东西。
标签: javascript oop parent-child