Javascript `this` 没有像我想象的那样工作?

标签 javascript class prototype this

我正在将一个非常基本的 js 函数改编成一个类。不管怎样,基本上它只是创建一个 float 容器 位于主页上方。我知道它不完整,但我正在输入它,并且在尝试调用 close() 函数时不断陷入困境。 Firefox 返回一个 this.sdiv 未定义。我很困惑,当 close() 是 Pop 的方法并且 sdiv 定义在 Pop 类的第一行中时,怎么会出现这种情况?

function Pop( wpx,hpx ){

  Pop.prototype.sdiv;
  Pop.prototype.shadow;
  Pop.prototype.pdiv;

  // start with the invisible screen, which
  // covers the main page
  this.sdiv = document.createElement("DIV")
  this.sdiv.className = "popScreen";
  this.sdiv.id = "popScreen";
  // this screen covers the full document, so 
  // base dimensions on the document size
  this.sdiv.style.width = document.body.clientWidth + "px";
  this.sdiv.style.height = document.body.clientHeight + "px"; 
  document.body.appendChild( this.sdiv );

  // attach drop shadow
  this.shadow = document.createElement("DIV");
  this.shadow.className = "popShadow";
  this.shadow.style.width = wpx + "px";
  this.shadow.style.height = hpx + "px";
  this.shadow.style.left = ( ( window.innerWidth / 2 ) - ( wpx / 2 )  ) + "px";
  this.shadow.style.top = ( ( window.innerHeight / 2 ) - ( hpx / 2 ) ) + "px";
  document.body.appendChild( this.shadow );

  this.pdiv = document.createElement("DIV");
  this.pdiv.className = "pop";
  this.pdiv.id = "pop";
  this.pdiv.style.position = "absolute";
  this.pdiv.style.width = wpx + "px";
  this.pdiv.style.height = hpx + "px";
  this.shadow.appendChild( this.pdiv );

  // bind an event to the screen div so that when it is clicked
  // the Pop dialogue is closed and the user is return to the main page
  $("div#popScreen").click( function( ){
    Pop.prototype.close( );
  } );

  Pop.prototype.go = function( url, method, data ){ 
    if( method == null )
      $("div#pop").load( url );
  }

  Pop.prototype.close = function( ){
      this.sdiv.parentNode.removeChild( this.sdiv );
      this.shadow.parentNode.removeChild( this.shadow );
      this.pdiv.parentNode.removeChild( this.pdiv );
  }

} 

预先感谢您的帮助

最佳答案

您不能使用 Pop.prototype.close() 关闭所有 Pop 实例。相反,对于使用 new 运算符创建的每个 Pop 实例,您需要调用 popInstance.close()

关于Javascript `this` 没有像我想象的那样工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/460949/

相关文章:

javascript - 如何比较过去的输出值?

javascript - Mongoose 和 Node 查询的时机

javascript - 如何使用 location.href 而不是 location.pathname

javascript - 无法在 Firefox 中覆盖 Element 的 addEventListener

python - 在Python中,可以从静态方法引用实例变量吗?

javascript - 为什么我无法通过原型(prototype)访问类中 “this” 上的属性?

javascript - 属性(property)被列出的无数属性(property)所掩盖?

c# - 命名一个对象,该对象是具有与对象类型相同的 getter/setter 的另一个对象的属性

PHP - 使用常量的值来引用数据成员

javascript - 如何在没有 jQuery 的情况下编写 javascript 插件