0

我正在将一个非常基本的 js 函数改编成一个类。无论如何,基本上它只是在主页上方创建一个浮动容器。我知道它不完整,但我正在输入它,并且在尝试调用 close() 函数时不断被抓住。Firefox 返回 athis.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 );
  }

} 

提前感谢您的帮助

4

2 回答 2

3

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

于 2009-01-20T11:48:49.657 回答
1

this在 javascript 中的工作方式与在 oo 语言中非常不同。

您遇到的错误在这里:

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

在那个函数this中可能是指窗口(设置断点并查看萤火虫)

也许这些方面的东西会起作用。

 var parent = this;
 Pop.prototype.close = function(){
      parent.sdiv.parentNode.removeChild( this.sdiv );
      parent.shadow.parentNode.removeChild( this.shadow );
      parent.pdiv.parentNode.removeChild( this.pdiv );
  }
于 2009-01-20T11:55:33.917 回答