我尝试了一下但没有成功:
<!DOCTYPE html>
<html>
<title>Web Page Design</title>
<head>
<script>
function MyClass() {
function someFunc() { calledFunc(); }
function calledFunc() { document.writeln('orig called'); }
return {
someFunc: someFunc,
calledFunc: calledFunc
}
}
var obj = new MyClass();
obj.someFunc();
obj.calledFunc = function() { document.writeln("not orig called"); }
obj.someFunc();
</script>
</head>
<body>
</body>
</html>
我看到仅调用
orig called
而不调用not orig called
如何覆盖calledFunc
以便调用not orig called
? 最佳答案
obj.calledFunc
不是您在someFunc
中要调用的那个。
您要替换obj.calledFunc
所指的内容,但是在someFunc
中,您要调用在MyClass
闭包中定义的那个。
您必须执行以下操作:
function MyClass() {
var self = this;
this.calledFunc = function() {
document.writeln('orig called');
};
this.someFunc = function() {
self.calledFunc(); // This refers to the same function you've exposed
};
}
var obj = new MyClass();
obj.someFunc();
obj.calledFunc = function() {
document.writeln("not orig called");
}
obj.someFunc();