JavaScript。为什么创建新对象时会覆盖私有(private)函数?

标签 javascript object intervals

您好,我有对象和 setInterval 的问题。看起来变量在所有实例之间共享。下面是示例代码:

function intervals(objectName) {
    var interval;
    var name = objectName;

    this.makeInterval = function() {
        clearInterval(interval);
        interval = setInterval(function() { console.log('hello world'); }, 20000);
    };

    this.intervalIdToConsole = function() {
        console.log(name + ' interval ID: ' + interval);
    };

    this.stop = function() {
        stopInterval();
    };

    stopInterval = function() {
        console.log('Stopping ' + name + ' id: ' + interval);
        clearInterval(interval);
    };
}

var int1 = new intervals('object1');
var int2 = new intervals('object2');
int1.makeInterval();
int1.intervalIdToConsole();

int2.makeInterval();
int2.intervalIdToConsole();
console.log('-----------------');
int1.intervalIdToConsole();
int2.intervalIdToConsole();
console.log('-----------------');
int1.stop();
int2.stop();

当我在网络浏览器的输出中运行此代码时,我收到如下消息:

object1 interval ID: 5
object2 interval ID: 6
-----------------
object1 interval ID: 5
object2 interval ID: 6
-----------------
Stopping object2 id: 6
Stopping object2 id: 6

这是我的问题。我做错了什么?为什么在 int1.stop() 上调用 object2 中的 stopInterval() ?

编辑 天哪,现在可以了。谢谢你!为了更好的理解。如果我在没有 var 语句的情况下声明变量,那么它是全局变量?

最佳答案

因为 stopInterval 是一个全局变量,因此会被下一个赋值覆盖。

为了防止这种情况,使用 var 关键字在 intervals 函数作用域内声明变量,或者使用 this.stopInterval = ... 声明该变量作为该函数的成员。 .

提示:使用严格模式防止意外声明全局变量:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode

关于JavaScript。为什么创建新对象时会覆盖私有(private)函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32710955/

相关文章:

Javascript 框架 canJs control.route

javascript - jQuery UI Sortable 当项目重新排列或在列表之间移动时触发

javascript - 搜索匹配属性和等效属性值

javascript - 在函数运行之前等待计时器完成

javascript - 避免 `fetch()` 将模型属性标记为已更改

javascript 比较两次

java - 对象比较是否相等 : JAVA

javascript - 通过函数获取对象中特定键的值

c - 在 C 中实现定时事件

datetime - 间隔一个月回来31号不上类?