繁体   English   中英

在对象的方法内使用“this”关键字

[英]Using “this” keyword inside method of an object

这是我的代码的片段:

var  main = function(){
    this.f = function(){
        console.log ( "nothing much");
    }
};

main.prototype.fun = function(){
    console.log ( "I am Fun");
    /*
      1st Here this will refer to Object of `main`. 
      But I want someway to bind f1 to fun not to main
    */
    this.f1 = function(){
        console.log ( "Help!");   
        return this;
    };

    this.f2 = function(){
        console.log ( "Print");
        return this;
    };

    /*
      2nd. Here again this will refer to Object of `main`. 
      But I want to return object of fun.
    */
    return this;
}

现在,我可以通过以下代码获得第一点,但这看起来很长(第二个问题仍然存在):

main.prototype.fun.prototype.f1 = function(){
    console.log ( "Help FUN");
    return this;
};

main.prototype.fun.prototype.f2 = function(){
    console.log ( "Print FUN");
    return this;
};

你们是如何处理这种情况的?

你可以在这里有两个不同类的函数:

var Fun = function(){ };

Fun.prototype.f1 = function(){
  console.log ( "Help FUN");
  return this;
};
Fun.prototype.f2 = function(){
  console.log ( "Print FUN");
  return this;
};

然后在Main定义Fun的属性:

var Main = function(){ };
Main.prototype.fun = new Fun();

或者喜欢:

var Main = function(){
  this.fun = new Fun();
};

然后你就可以使用它:

var main = new Main();

main.fun.f1().f2();

要么

main.fun.f2().f1();

在这种情况下,您可以使用arguments.callee;

var  main = function(){
    this.f = function(){
        console.log ( "nothing much");
    }
};
main.prototype.fun = function(){
    console.log ( "I am Fun");
    var scope=arguments.callee;
    scope.f1 = function(){
        console.log ( "Help FUN");
        return scope;
    };
    scope.f2 = function(){
        console.log ( "Print FUN");
        return scope;
    };
    return scope;
}

// test it
var test1=new main();
test1.f();
var test2=test1.fun();
test2.f1();
test2.f2();

要么,

var  main = function(){
    this.f = function(){
        console.log ( "nothing much");
    }
};
var fun=main.prototype.fun = function(){
    console.log ( "I am Fun");
    fun.f1 = function(){
        console.log ( "Help FUN");
        return fun;
    };
    fun.f2 = function(){
        console.log ( "Print FUN");
        return fun;
    };
    return fun;
}

// test it
var test1=new main();
test1.f();
var test2=test1.fun();
test2.f1();
test2.f2();

暂无
暂无

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

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