开发者

Javascript accessing functions of same class

In the following code:

function xyz(x) {
          //something
          this.x = x;
        }
        xyz.prototype = {
            a: function () {
                //do something
            },
            b: function () {
                //pre
                this.a();
     开发者_如何转开发           //post
            }
        }

the call of this.a() gives the warning of method not supported. So I tried using xyz.prototype.a.call(this) instead. But it does not maintain the value of x. What do I do to call one method of a class from other?


Given your code, if you write:

var myXyz = new xyz("hello");

then calling

myXyz.b();

should correctly get to the "a()" function on the prototype. However, if you do something like this:

var otherB = myXyz.b;

otherB();

then it will not work, because there's no context object (that is, the this value inside "b()" won't be set correctly to an instance of "xyz"). That often happens when a function is being used as an event handler:

 something.onclick = myXyz.b;

The event handler, when called, won't have an "xyz" instance to work with. Instead of that, therefore, you could write:

 something.onclick = function() { myXyz.b(); };

which clearly ensures that there's an "xyz" object.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜