[英]Access other functions inside the same function
there is some way to do this? 有什么办法可以做到这一点?
function test()
{
this.write = function(text)
{
alert(text);
}
this.read = function()
{
this.write('foo');
// WRONG WAY
// test.write('foo');
}
}
How can i call the "this.write" function from "this.read"? 如何从“ this.read”中调用“ this.write”功能?
EDIT: 编辑:
Found the awnser by EricG. 通过EricG找到了遮篷。 Have tried with the code above and it works.
尝试过上面的代码,它可以工作。 But my real code still not working.
但是我的真实代码仍然无法正常工作。 I've to figure out what's happening.
我必须弄清楚发生了什么。
The Way to call "THIS.WRITE" from inside "THIS.READ" is just by calling 'this.write()". Just like that. 从“ THIS.READ”内部调用“ THIS.WRITE”的方法就是调用“ this.write()”。
Thanks! 谢谢!
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);
}
You can also use this without the bind call, but under certain circumstances the meaning of 'this' may change. 您也可以在没有bind调用的情况下使用它,但是在某些情况下,“ this”的含义可能会改变。
That totally depends on, where the function is called from. 这完全取决于从何处调用函数。 I would suggest reading some more about the
this
keyword Maybe take a look at this SO question 我建议阅读有关
this
关键字的更多信息也许看看这个SO问题
If you create an Instance of test
如果您创建
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'
And call the method read
of this instance, this
will refer to the well ,this instance of test
并调用该方法
read
该实例的, this
将涉及嗯 ,这种情况下test
However if your code doesn't work, the method is probably called with another context. 但是,如果您的代码不起作用,则可能会在另一个上下文中调用该方法。 Maybe an Eventlistener you added.
也许您添加了一个事件监听器。 And the callback function of it tries to call
this.write
并且它的回调函数尝试调用
this.write
then this
wouldn't refer anymore to the instance of test/your function. 那么
this
将不再引用test /您的函数实例。
What you could also do is preserving the context in a local variable like 您还可以做的是将上下文保存在局部变量中,例如
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
So as you see in the second case the write
gets executed although read
is called with the Global Object Window
as its context. 因此,如您在第二种情况中所见,尽管以全局对象
Window
为上下文调用了read
但write
仍被执行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.