Javascript`这个'没有像我想的那样工作?

时间:2009-01-20 11:43:44

标签: javascript class prototype this

我正在将一个非常基本的js函数改编成一个类。无论如何,基本上它只是创建一个浮动容器 在主页上方。我知道它不完整,但我正在打字,并在尝试调用close()函数时不断被抓住。 Firefox返回this.sdiv未定义。我很困惑,当close()是Pop的方法并且在Pop类的第一行定义了sdiv时,情况会怎样?

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 );
  }

} 

提前感谢您提供任何帮助

2 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分:1)

javascript中的

this在oo语言中使用very differently

您遇到的错误是:

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

在该函数中this可能是referring to the window(设置断点并查看firebug)

也许这些方面的东西都可行。

 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 );
  }