使用'setinterval'时如何处理'this'关键字? [英] How do I handle the 'this' keyword when using 'setinterval'?

查看:129
本文介绍了使用'setinterval'时如何处理'this'关键字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Clock = function (ele)
{
	if (ele)
	{
		if (typeof ele == 'string')
		{
			this.node = document.getElementById(ele);
		}
		else
		{
			this.node = ele;
		}
	}
	else
	{
		throw new Error('')
	}
};

Clock.prototype = {
	getTime: function ()
	{
		var d = new Date;
		var s = d.getSeconds().toString(), m = d.getMinutes().toString(),
			pm = d.getHours() > 12,
			h = (pm ? (d.getHours() - 12) : d.getHours()).toString();
		return ((h.length === 2) ? (Number.h.charAt(1)) : ('0' + h)) + ':' +
			   ((m.length === 2) ? m : ('0' + m)) + ':' +
			   ((s.length === 2) ? s : ('0' + s)) + ' ' +
				(pm ? 'PM' : 'AM');
	},
	tick: function () { this.node.innerText = this.getTime() },
	start: function ()
	{
		this.interval = setInterval(this.tick, 1000);
	},
	stop: function ()
	{
		clearInterval(this.interval)
	}
};





此代码是一个名为Clock的类与new关键字一起使用。我还使用其prototype属性定义了它的几个属性,当调用 start 函数时,它设置一个计时器来调用勾选每1秒运行一次。我面临的问题是关键字this不是指我的类,而是指Window对象,所以我需要一种方法来引用节点 getTime 我的类的新实例中的属性,而不使用this关键字。有什么建议吗?



我尝试了什么:



我知道我可以在任何方法中创建一个全局变量和引用,但这会使得一个类与构造函数一起使用的目的失败。



This code is a class called Clock that is used with the "new" keyword. I've also defined several properties of it using its prototype property, and when the "start" function is called it sets a timer to call the "tick" function every 1 second. The issue I'm facing is the keyword "this" doesn't refer to my class but instead the "Window" object, so I need a way to reference the "node" and "getTime" properties inside a new instance of my class without using the this keyword. Any advice?

What I have tried:

I know I can create a global variable and reference that inside any of the methods but that defeats the purpose of having a class to be used with a constructor.

推荐答案

你太糟糕了不使用严格模式;那么你认为这个引用的 [Window] 对象就是对象 undefined ,这对于安全编程。此外,严格模式不允许 Clock = function(),但缺少 var 关键字。

所以,我的第一个建议是:在开发期间,始终使用

Too bad you are not using strict mode; then what you think is the [Window] object referenced by this would be the object undefined, which is much better for safe programming. Also, strict mode would not allow your Clock = function () with missing var keyword.
So, my first advice: during development, always start all your scripts with
"use strict";



参见:严格模式 - JavaScript | MDN [ ^ ]。



如果你真的想要,你可以在开发完成后关闭严格。



你的另一个问题是思维方式。你说......不使用这个关键字,好像这个很麻烦。这不是一个麻烦,它是你真正需要理解的功能。首先,您应该理解JavaScript中的this与OOP语言中的this非常不同;首先,这是因为作为一流公民对象的功能的本质。你犯了一些我看不到的简单错误,因为你没有显示一些相关的代码部分。如果某些东西不适合你,你应该试着理解它,而不是摆脱它。但是我可以解释一下可以继续发生什么。



最后,你的问题是:你在编写一些基础知识之前编写了太多代码。让我缩短它以显示你可以观察到的内容:


See also: Strict mode - JavaScript | MDN[^].

If you really want, you can switch "strict" off when your development is done.

Your other problem is the way of thinking. You say "…without using the this keyword", as if "this" was the hassle. It's not a hassle, it's a feature you really need to understand. First of all, you should understand that "this" in JavaScript is very different from "this" in OOP language; and this is so, first of all, because of the nature of functions which are first-class citizen objects. You make some simple mistake which I cannot see because you did not show some relevant part of code. If something does not work for you, instead of getting rid of it, you should try to understand it. But I can explain what can go on.

And, finally, your problem is: you are writing too much code before you sort out some fundamentals. Let me shorten it down to show what you could observe:

function f() { writeLine(this); }

var Clock = function () {
	this.node = 2;
}

Clock.prototype = {
	start: function ()
	{
		writeLine(this.node);
		f();
	},
};

function f() { writeLine(this); }

var cl = new Clock();
cl.start();

在此代码示例中, writeLine 是我的debug / playground函数。如果你打电话给开始,你会看到this真的是引用你的 Clock 对象,因为你在里面引用它一个函数,它是此对象的实例成员。当你打电话给 f (或 setInterval 时,这个将是 undefined ,因为这些函数与任何其他对象一样多;并且这些对象不是另一个对象的属性;它们位于顶层。而且,在显示的代码中,没有这样的this情况;你只有 this.tick this.interval 。首先它将作为时钟对象属性,不幸的是,你没有显示你在哪里定义 interval 。如果没有定义,如你的代码片段所示,这是真正的问题,这个是无罪的。: - )



-SA

In this code sample, writeLine is my debug/playground function. If you call start, you will see that "this" is really reference your Clock object, because you reference it inside a function which is an instance member of this object. When you call f (or setInterval, "this" would be undefined, because these functions are as much of objects as any other objects; and these objects are not properties of another object; they are on the top level. And, in your code shown, there are no such "this" cases; you have only this.tick and this.interval. First will work as the clock object property, and, unfortunately, you did not show where you define interval. If it is not defined, as shown in your code fragment, this is the real problem, and "this" is not guilty. :-)

—SA


最后我改变了我的代码,以便开始功能如下:

In the end I changed my code so that the start function went like this:
var t = this;
this.interval = setInterval(this.tick, 1000, t);





tick 函数接受了一个参数来替换这个关键字。像这样:



and the tick function accepted a parameter to replace the "this" keyword. Like this:

tick: function (t)
{
    t.node.innerText = t.getTime()
}


这篇关于使用'setinterval'时如何处理'this'关键字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆