访问同一函数内的其他函数
Access other functions inside the same function
有什么方法可以做到这一点吗?
function test()
{
this.write = function(text)
{
alert(text);
}
this.read = function()
{
this.write('foo');
// WRONG WAY
// test.write('foo');
}
}
如何从"this.read"调用"this.write"函数?
编辑:
找到了EricG的awnser。已经尝试过上面的代码,它是有效的。但我的真实代码仍然不起作用。我必须弄清楚发生了什么。
从"THIS.READ"内部调用"THIS.WRITE"的方法就是调用"THIS.WRITE(("。就像那样。
谢谢!
function test()
{
this.write = function(text)
{
alert(text);
}
this.read = function()
{
this.write('foo');
}
}
var a = new test();
a.read();
jsFiddle
试试这个:
function test()
{
this.write = function(text)
{
alert(text);
}
this.read = function()
{
this.write('foo');
}
}
var t = new test();
t.read();
小提琴
function test()
{
var self = this;
this.write = function(text)
{
alert(text);
};
this.read = function()
{
self.write('foo');
};
// depending on browser versions or included libraries.
this.another = function () {
this.write('foo');
}.bind(this);
}
您也可以在不使用绑定调用的情况下使用它,但在某些情况下,"this"的含义可能会更改。
这完全取决于从哪里调用函数。我建议阅读更多关于this
关键字的内容也许可以看看这个SO问题
如果创建test
的实例
function test()
{
this.write = function(text)
{
alert(text);
}
this.read = function()
{
this.write('foo');
}
}
var inst = new test()
inst.read() //foo
inst.read.call() //Uncaught TypeError: Object [object Window] has no method 'write'
并调用此实例的方法read
,this
将引用井,此实例为test
但是,如果您的代码不起作用,则可能会使用另一个上下文调用该方法。也许是您添加的Eventlistener。它的回调函数尝试调用this.write
那么CCD_ 7将不再引用test/your函数的实例。
您还可以将上下文保存在像这样的局部变量中
function test()
{
var context = this;
this.write = function(text)
{
alert(text);
}
this.read = function()
{
context.write('foo');
}
}
var inst = new test()
inst.read() // foo
inst.read.call() //foo
因此,正如您在第二种情况中看到的那样,尽管read
是以全局对象Window
作为其上下文来调用的,但write
会被执行。
这是一个JSBin
相关文章:
- Jquery未定义函数正在停止其他操作
- 执行php函数的onclick事件的其他替代方案
- 如何在.js函数中检索来自其他模板的表单的目标值
- 对其他函数使用匿名函数's参数
- 创建要在其他函数中使用的全局变量
- 调试一个简单的jQuery函数;想知道是否与其他代码冲突
- 在Meteor中如何将数据从函数内部复制到其他模板
- 在Jquery调用之间添加其他函数
- 使用一个Javascript函数提交多个表单可以在FF中工作,而不需要其他浏览器
- Mocking console.log()/MOCHA测试框架中的任何其他函数
- 如何从ipify函数返回ip地址,以便在其他函数中使用
- 如果没有其他函数链接到promise,则默认行为
- Javascript创建函数,以便在其他函数之间共享变量
- AngularJS:如何与其他控制器共享作用域函数和变量
- Firefox扩展开发:如何在内容脚本中创建一个全局函数,以便其他加载的脚本文件可以访问它
- 使通过函数加载的JSON可用于其他函数
- 如何使用 javascript 函数取决于是否其他
- 如何在 JavaScript 中访问函数中的其他属性值作为对象属性值
- 有没有办法将其他参数传递给 scrollTarget 回调函数
- 如何在创建的字段上应用 .change 函数 b 其他字段的 .change 函数