2013-01-08 178 views
0

有一些方法可以做到这一点吗?访问同一功能内的其他功能

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()”。就这样。

谢谢!

+5

“test”是如何被调用的?如何调用'read'?这将决定每个“this”的价值。你为什么使用'this'?你是否将'test'作为构造函数调用?如果是这样,为什么不使用大写(即'function Test()')开始构造函数名称的约定呢? – Quentin

+0

如果你想做'new test()。read()' – EricG

+0

圣母...我尝试了很多次这样做,并且是“this.foo()”来执行另一个函数。它与该示例一起工作,但出于某种原因,我的代码(其他代码,我没有把它放在这里),它不工作。无论如何。感谢EicG和Quentin的帮助 – Alexandre

回答

1
function test() 
{ 
    this.write = function(text) 
    { 
     alert(text); 
    } 

    this.read = function() 
    { 
     this.write('foo'); 
    } 
} 

var a = new test(); 
a.read(); 

jsFiddle

0

试试这个:

function test() 
{ 

    this.write = function(text) 
    { 
     alert(text); 
    } 

    this.read = function() 
    { 
     this.write('foo'); 
    } 
} 

var t = new test(); 
t.read(); 

fiddle

0
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”的含义可能会改变。

0

这完全取决于函数从何处被调用。 我建议阅读一些有关this关键字如果您创建的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也许看看这个SO question

this将指welltest

但是,如果您的代码不起作用,该方法可能会与另一个上下文一起调用。 也许你添加了一个Eventlistener。并且它的回调函数试图调用this.write
然后this不会再引用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 

所以当你在write得到尽管read被调用为它的上下文全局对象Window执行第二种情况看。

继承人a JSBin