首页 > js 对象中this

js 对象中this

原先有几个方法,都是类似这样调用:

var func1 = function(words) {
  this.test = words;
  this.echo();
};func1.prototype = {
  echo: function(){
     console.log(this.test);
  }
};
new func1("hello world");

现在想把这些方法整合到一个对象$A里,想这样调用:

window.$A = {};
...
//不知道该如何做
...
//最后可以这样调用
$A.fun1("hello world");

想尽可能少改动已经写好的func1, 试了一下这样:

  $A.func1 = (function(){
    var func1 = function(words) {
      this.test = words;
      this.echo();
    }; func1.prototype = {
      echo: function(){
        console.log(this.test);
      }
  };
  return func1;
})();
//这样调用的时候this已经不是这个this了。。

感谢。


如果要改前面那个段:

new $A.fun1("hello world");

即可

如果要改后面那个段:

$A.func1 = (function(){
    var func1 = function(words) {
      if (this === window.$A)
        return new func1(words);
      this.test = words;
      this.echo();
    }; func1.prototype = {
      echo: function(){
        console.log(this.test);
      }
  };
  return func1;
})();

方法内this的两个情况:
- 当作为普通方法调用的时候,方法属于谁的属性谁就是this。全局方法属于全局对象(浏览器中是window)。你的第二个代码段里面fun1属于这种情况,fun1属于$A($A.fun1(...)),那么fun1里面的this就是$A。
- 当作为构造方法使用的时候(前面加new),即将创建的对象就是this。你的第一个代码段里面的fun1属于这种情况。(new func1(...)

【热门文章】
【热门文章】