简体   繁体   English

同一JavaScript类[Prototype]中的调用方法

[英]Calling methods within same JavaScript class [Prototype]

I've created a class in Javscript using the prototype Class.Create complete with the initialize function and a few other functions. 我已经使用原型Class.Javscript在Javscript中创建了一个类,并创建了带有initialize函数和其他一些函数的完整类。 However, in one of my functions I want to reference another function in the same class, but cannot seem to get the syntax correct. 但是,在我的一个函数中,我想引用同一类中的另一个函数,但是似乎无法获得正确的语法。

eg 例如

    var sampleClass = Class.create({

            initialize: function(){

                //do the init work here

        },

        functionA: function(){

            //do some more stuff here
        }
        functionB: function(){
            //Do some stuff
            functionA()
        }
}

I've tried calling functionA() , this.functionA() but nothing works I just get errors. 我试过调用functionA(),this.functionA(),但是没有任何效果,我只是报错。 I know how to call the functions externally when the class has been instantiated, but not reference a function from within the class itself. 我知道在实例化类后如何从外部调用函数,但不从类本身内部引用函数。

Thanks 谢谢

this.functionA() this.functionA()

would be the correct way to call the object's method from within another method of the same object. 是从同一对象的另一个方法中调用该对象的方法的正确方法。

but nothing works I just get errors 但什么都行不通我只会出错

What errors? 有什么错误? If you are getting 'property functionA not found', then the probability is that this is pointing in the wrong place. 如果您正在获取“找不到属性功能A”,则可能是因为this指向错误的位置。 Use Firebug or some alert ​s to check what it is. 使用Firebug或一些alert来检查它是什么。 A common problem is that you've detached the method's function from the owner object and passed it to something else: 一个常见的问题是您已将方法的功能与所有者对象分离,并将其传递给其他对象:

element.onclick= this.functionB;

when functionB is called back in this case, this will be unset and so will default (very unhelpfully, for debugging) to window . functionB在这种情况下,被称为回来, this将取消设置和它的默认值(很帮倒忙,用于调试)到window This happens because object.methodname in JavaScript, unlike many other modern scripting languages, only gives you an unbound function object and not a bound method. 发生这种情况是因为与许多其他现代脚本语言不同,JavaScript中的object.methodname仅提供了未绑定的函数对象,而不提供了绑定的方法。

The simple way to preserve this , introduced by Prototype and now a standardised part of JavaScript (coming soon to a browser script engine near you), is function.bind : 最简单的方法来保存this由原型介绍,现在的JavaScript标准的一部分(即将在您附近的浏览器脚本引擎),是function.bind

element.onclick= this.functionB.bind(this);

Agreed with bobince, except you'll want to use the Event.observe() syntax for attaching event handlers rather than assigning to the element's onclick property. 同意bobince,除了您要使用Event.observe()语法附加事件处理程序,而不是分配给元素的onclick属性。 Example: 例:

element.observe('click', this.functionB.bind(this));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM