使用“this"对象方法内部的关键字

Using "this" keyword inside method of an object

本文关键字:方法 内部 关键字 对象 this quot 使用      更新时间:2023-09-26

下面是我的代码片段:

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