我的类型看起来像这样:
var x = function(){
this.y = function(){
}
this.z = function(){
...
this.A = function(){
CALLING POINT
}
}
}
Run Code Online (Sandbox Code Playgroud)
从呼叫点,我试图调用函数this.y. 我不需要传递任何参数,但是当我从this.A设置一些东西时,我需要调用this.y.
这可能吗?我可以将额外的参数传递给函数以使其成为可能.
这可能吗?
是的,您可以this为另一个变量分配引用,然后y在其上调用函数
this.z = function() {
var self = this;
this.A = function() {
self.y();
}
}
Run Code Online (Sandbox Code Playgroud)
版本bind,基本上这a为对象添加了一个新方法。
var X = function () {
this.y = function () {
document.write('y<br>');
}
this.z = function () {
document.write('z<br>');
this.a = function () {
document.write('a<br>');
this.y();
}
}.bind(this);
};
var x = new X;
//x.a(); // does not exist
x.z(); // z
x.a(); // a yRun Code Online (Sandbox Code Playgroud)
保存内部的工作示例this。
var X = function () {
var that = this; // <--
this.y = function () {
document.write('y<br>');
}
this.Z = function () {
document.write('Z<br>');
this.a = function () {
document.write('a<br>');
that.y();
}
}
}
var x = new X,
z = new x.Z; // Z
z.a(); // a yRun Code Online (Sandbox Code Playgroud)