使用“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();
相关文章:
- 可以“;超级“;可以在子类的方法内部使用,在不直接引用的情况下调用相应的超类方法
- 如何从方法内部获取js方法名称
- 方法不在另一个方法内部调用
- 在模式方法内部,“this”在猫鼬 4.4.12 中为空 {}
- Angular promise回调不是在构造函数方法内部触发,而是在对象文本方法中触发
- 从对象方法内部的数组中运行console.log
- 从方法内部设置对象变量
- 在方法内部调用另一个方法 ReactJS
- 取消对象方法内部的动画帧不起作用
- GetVariable在方法内部工作
- HTTP GET位于客户端调用的api方法内部
- OOP,命名空间的顶级方法内部的私有函数
- Wicket:将JavaScript附加到非Ajax按钮(onSubmit()方法内部)
- 带有查询参数的节点js-app.get方法-内部服务器错误
- 数组排序方法内部的作用域
- 如何在JavaScript中访问继承方法内部的私有属性
- Cordova插件的执行方法内部的AsyncTask工作不正常
- 访问方法内部的变量's函数
- 如何从resolve方法内部更新作用域
- Javascript:从对象方法内部调用回调函数,产生意想不到的结果