开发者

OO Javascript Question

开发者 https://www.devze.com 2023-02-12 21:13 出处:网络
Given the fo开发者_如何学Pythonllowing: var someObject = {}; someObject.prototype.a = function() {

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

精彩评论

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