我尝试了一下但没有成功:



<!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();

09-13 02:55