使用"这个"关键字里面的对象方法

时间:2014-05-19 07:44:31

标签: javascript prototype this

以下是我的代码片段:

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

你们如何处理这种情况?

2 个答案:

答案 0 :(得分:3)

你可以在这里有2个不同类的功能:

var Fun = function(){ };

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

然后在Fun中定义Main的属性:

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

答案 1 :(得分:0)

在这种情况下,您可以使用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();