JavaScript的。为什么在创建新对象时会覆盖私有函数?

时间:2015-09-22 07:33:44

标签: 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();

当我在输出中的Web浏览器中运行此代码时,我会得到如下消息:

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语句的情况下声明变量那么它是全局变量吗?

2 个答案:

答案 0 :(得分:2)

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

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

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

答案 1 :(得分:1)

你忘了var。这段代码正在运行:

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

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

我在var之前添加了stopInterval

输出:

object1 interval ID: 1
object2 interval ID: 2
-----------------
object1 interval ID: 1
object2 interval ID: 2
-----------------
Stopping object1 id: 1
Stopping object2 id: 2