开发者

OO Javascript Question

Given the fo开发者_如何学Pythonllowing:

var someObject = {};

someObject.prototype.a = function() {

};

someObject.prototype.b = function() {

//How can I call someObject.a in this function?

};

How can I call someObject.a from someObject.b? Thanks.


This will work:

someObject.prototype.b = function() {
  this.a();
};

However your definition of someObject is slightly wrong, it should be:

var someObject = function() {};

Test script:

var someObject = function() {};

someObject.prototype.a = function() {
    alert("Called a()");
};

someObject.prototype.b = function() {
    this.a();
};

var obj = new someObject();
obj.b();


I think you probably meant to do this:

function Thingy() {
}

Thingy.prototype.a = function() {

};

Thingy.prototype.b = function() {
    this.a();
};

var someObject = new Thingy();

It's constructor functions, not plain objects, that have a special prototype property. The prototype of a constructor function is assigned to all objects created with that constructor via the new keyword as their underlying prototype, which gives them default properties (which may reference functions, as they do above).

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜