简体   繁体   English

Javascript “this”变量从特定 object 切换到 DOMWindow

[英]Javascript “this” variable switching from specific object to DOMWindow

I have a problem with Javascript forcing the [object DOMWindow] into an function I have in an object's prototype.我有一个问题,Javascript 将 [object DOMWindow] 强制转换为我在对象原型中的 function。 The full error I get is below:我得到的完整错误如下:

Uncaught TypeError: Object [object DOMWindow] has no method 'positionconvert'

Basically what I'm doing is inside the object prototype under certain conditions I'm creating a var interval that counts off with window.setInterval() :基本上我正在做的是在某些条件下的 object 原型内部,我正在创建一个var interval ,该间隔与window.setInterval()一起计数:

var interval = window.setInterval(this.alertanimate, 500);

the alertanimate function is inside the same prototype, and uses the this variable in this line: alertanimate function 在同一原型内,并在此行中使用this变量:

this.positionconvert(this.alerticon, -69, 55);

(positionconvert is yet another function, and alerticon is an object). (positionconvert 是另一个 function,而 alerticon 是一个对象)。 The problem is when I get window.setInterval involved js starts assuming this is the DOM and not the object prototype, like I intended, presenting the above error.问题是当我得到window.setInterval涉及的 js 开始假设this是 DOM 而不是 object 原型时,就像我想要的那样,呈现上述错误。 When I hard-code this to work with a specific object it works, but somewhere in this variable-passing the this variable loses its connection to the object.当我对其进行硬编码以与特定的 object 一起工作时,它可以工作,但是在这个变量中的某处传递this变量会失去与 object 的连接。 I hope this all makes sense?我希望这一切都有意义? What am I doing wrong?我究竟做错了什么?

Passing this.alertanimate to setIntervall loses the connection to the main object. this.alertanimate传递给setIntervall会失去与主 object 的连接。 What this refers to in a function is entirely defined by how the function is called. this在 function 中所指的内容完全由function的调用方式定义。 If you pass a function to setTimeout then this will refer to window .如果您将 function 传递给setTimeout ,那么this将引用window

You can do:你可以做:

var self = this;

window.setInterval(function() {
    self.alertanimate();
}, 500);

In newer browsers, you can also use .bind() [MDN] (see docs for an alternative implementation):在较新的浏览器中,您还可以使用.bind() [MDN] (有关替代实现,请参阅文档):

window.setInterval(this.alertanimate.bind(this), 500);

Welcome to JavaScript.欢迎来到 JavaScript。 The this is re-bound every time you introduce a function scope.每次您介绍 function this时,都会重新绑定。


    var outer = function() {
      var that = this;
      // that and this refer to the same object: outer
      var inner = function() {
        // now that refers to outer and this refers to inner
        ...
      }
      // that and this again refer to the same object: outer
      ...
    }

You didn't post your full code, but I suspect one of your inner this 's doesn't mean what you think it does.你没有发布你的完整代码,但我怀疑你内心的一个this并不意味着你认为它做了什么。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM