【发布时间】:2019-05-03 12:40:32
【问题描述】:
我有这样的代码:
function Thing() {
function foo() {
alert('1');
}
return { foo : foo }
}
window['myThings'] = {
bar : function() {
let t = new Thing();
t.foo = function() {
Thing.prototype.foo.call(this);
alert('2');
}
}
}
并且有错误:“未捕获的类型错误:无法读取未定义的属性'调用'”。我想用自定义方法覆盖对象方法,从中调用父方法,然后添加一些代码。我的错在哪里?
P。 S. 从 cmets 阅读链接上的文章并更改代码如下:
Thing = function () {
this.someVar = 1;
foo();
}
Thing.foo = function() {
alert('1');
}
window['myThings'] = {
bar : function() {
let t = new Thing();
t.foo();
}
}
现在我有一个错误: foo is not a function...
P。 P.S. 像这样更改代码:
function Thing() {};
Thing.prototype = function (arg) {
this.someVar = arg;
this.foo();
}
Thing.prototype.foo = function() {
alert('1');
}
window['myThings'] = {
bar : function() {
let t = new Thing(1);
t.foo();
}
}
myThings.bar();
现在:传递给构造函数的 arg 未存储在 someVar 中或未从中读取...
【问题讨论】:
-
Thing 原型上没有任何内容。这不是你在 JS 中定义构造函数的方式
-
您从构造函数返回一个对象,因此该构造函数的实例不会继承自
Thing.prototype -
“什么是 JavaScript 中的 'new' 关键字可能重复? - Jared Smith 1 小时前” - 这不能解决问题...
标签: javascript object inheritance