javascript Javascript对象从自身调用函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16841322/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 06:12:05  来源:igfitidea点击:

Javascript objects calling function from itself

javascriptfunctionobjectprototype

提问by CodeEngie

I've been reading Game Design with HTML5 and JavaScript and it introduced me to objects. So after reading the book and working on the projects I decided to take this new found knowledge and integrate objects in my own projects. So here's my question can or should objects call their own functions? For example:

我一直在阅读使用 HTML5 和 JavaScript 的游戏设计,它向我介绍了对象。因此,在阅读本书并参与项目后,我决定利用这些新发现的知识并将对象集成到我自己的项目中。所以这是我的问题,对象可以或应该调用它们自己的函数吗?例如:

var someObject = {
    start: function() {
        check();
    },
    check: function() {
        console.log("Check!");
    }
};

someObject.start();

The book did show an example with a timer that does this:

这本书确实展示了一个带有定时器的例子,它可以做到这一点:

var timer = {
    start: function() {
        var self = this;
        window.setInterval(function(){self.tick();}, 1000);
    },
    tick: function() {
        console.log('tick!');
    }
};

In the example with timer object it makes a reference to self in order to call the internal function, so does this mean I should use self to call internal functions or is this the proper way to do this with objects? Or best practices? Thanks in advance.

在带有计时器对象的示例中,它引用 self 以调用内部函数,所以这是否意味着我应该使用 self 来调用内部函数,或者这是对对象执行此操作的正确方法?还是最佳实践?提前致谢。

var someObject = {
    start: function() {
        var self = this;
        self.check();
    },
    check: function() {
        console.log("Check!");
    }
};

someObject.start();

采纳答案by voithos

JavaScript names are lexically scoped, so whenever a name (variable) is encountered in a script, the JavaScript runtime must search up the scopes from where the function was defined.

JavaScript 名称是词法作用域的,因此每当在脚本中遇到名称(变量)时,JavaScript 运行时必须从定义函数的位置搜索作用域。

At the point of definition, this function:

在定义点,这个函数:

start: function() {
    check();
}

doesn't have access to any checkfunction in its outer scope. Declaring selfand binding it to thisis a technique used to deal with the (somewhat interesting) intricacies of referring to the current objectin JavaScript(because the example code uses window.setInterval).

无法访问check其外部范围内的任何函数。声明self和绑定它this是一种技术,用于处理在 JavaScript中引用当前对象的(有点有趣)复杂性(因为示例代码使用window.setInterval)。

To reference a function within the current object, it is enough to use this.

要在当前对象中引用函数,使用this.

var someObject = {
    start: function() {
        this.check();
    },
    check: function() {
        console.log("Check!");
    }
};

回答by julesbou

It's javascript function context, each time you create a function, you create a new context (scope).

它是 javascript 函数上下文,每次创建函数时,都会创建一个新的上下文(范围)。

In setInterval()function you create a new scope, so thisno longer refer as the same thisabove:

setInterval()函数中你创建了一个新的作用域,所以this不再像this上面一样引用:

var self = this;
setInterval(function() {
    self.tick();
}, 1000);

You can also manually bind the proper context of your function with bind()(so you don't need selfanymore):

您还可以手动绑定函数的正确上下文bind()(因此您不再需要self):

setInterval(function() {
    this.tick();
}.bind(this), 1000);


More informations:

更多信息:

回答by Pointy

The point of declaring and initializing a variable like "self" is to deal with the fact that the value of thisis determined anew upon each function call. When you've got a function nested inside another function, and that inner function needs access to the value of thisfrom the outer context, then thismust be preserved in another variable — "self" in your case. (The name of that variable is unimportant of course.)

声明和初始化像“self”这样的变量的重点是处理这样一个事实,即this每次函数调用时都会重新确定的值。当您将一个函数嵌套在另一个函数中,并且该内部函数需要访问this外部上下文中的值时,则this必须将其保存在另一个变量中 - 在您的情况下为“self”。(该变量的名称当然不重要。)

In your sample code:

在您的示例代码中:

var timer = {
    start: function() {
        var self = this;
        window.setInterval(function(){self.tick();}, 1000);
    },
    tick: function() {
        console.log('tick!');
    }
};

that function passed in to setInterval()needs to use the value of thisfrom the "start" function. When that interval timer function is called, however, thisis set to something else (either the global context or nullin "strict" mode). Thus, by saving the value of thisin the context where that interval timer function is instantiated, its code can use it to access the timer object.

传入的那个函数setInterval()需要使用this来自“start”函数的值。但是,当调用该间隔计时器函数时,它this被设置为其他内容(全局上下文或null“严格”模式)。因此,通过this在实例化间隔计时器函数的上下文中保存 的值,其代码可以使用它来访问计时器对象。

In your second example, declaring and initializing a "self" variable doesn't hurt anything, but it's unnecessary. Sometimes it's handy however, just to clarify the code, though of course a more meaningful name than "self" would be a good idea.

在您的第二个示例中,声明和初始化“self”变量不会造成任何伤害,但这是不必要的。然而,有时它很方便,只是为了澄清代码,当然一个比“self”更有意义的名字是个好主意。

回答by aaronman

of course an object can and should call it's own functions, this is the only way to emulate OOP in javascript. I would say that the practice that the book is using, self = thisis bad since thiscan just be used by itself, however in the first example it is used to preserve the value of this which would otherwise be the thisof the function itself not the outer class

当然,一个对象可以而且应该调用它自己的函数,这是在 javascript 中模拟 OOP 的唯一方法。我会说这本书正在使用的做法self = this是不好的,因为this它只能单独使用,但是在第一个示例中,它用于保留 this 的值,否则该值将是this函数本身的值,而不是外部类