Reputation: 14112
I'm trying to include some namespace into my Javascript API.
Here's what I have so far:
if (!Sample || Sample == "undefined")
var Sample = {};
Sample.SomeApi = {};
Sample.SomeApi.prototype = {
SomeMethod: function() {
alert('some api');
}
};
What's going on here?
When I'm calling Sample.SomeApi.SomeMethod();
// it won't work as it will complain:
Uncaught TypeError: Object #<Object> has no method 'SomeMethod'
(anonymous function)Course:43
onclick
Upvotes: -1
Views: 204
Reputation: 2123
Try this
if(typeof Sample == 'undefined')
var Sample ={}
Sample.SomeApi = function(a)
{
this.a =a;
}
Sample.SomeApi.prototype.SomeMethod = function() {
alert('some api');
}
var d = new Sample.SomeApi(1);
d.SomeMethod();
Hope this helps you
Go through this link here
Upvotes: 0
Reputation: 28120
I think you meant __proto__
not prototype
, like so:
if (!Sample || Sample == "undefined")
var Sample = {};
Sample.SomeApi = {};
Sample.SomeApi.__proto__ = {
SomeMethod: function() {
alert('some api');
}
};
Sample.SomeApi.SomeMethod();
You can test it out in this jsFiddle: http://jsfiddle.net/luisperezphd/xtyyf/
But why not just this:
if (!Sample || Sample == "undefined")
var Sample = {};
Sample.SomeApi = {
SomeMethod: function() {
alert('some api');
}
};
Sample.SomeApi.SomeMethod();
It's much cleaner.
And there is the jsFiddle for that: http://jsfiddle.net/luisperezphd/HUuMQ/
Upvotes: 2
Reputation: 44205
You have to create a constructor for Sample.SomeApi not assign an empty object:
if(typeof Sample == 'undefined')
Sample = {};
Sample.SomeApi = function() {
};
Sample.SomeApi.prototype = {
someMethod : function() {
alert('some api');
}
}
new Sample.SomeApi().someMethod();
Upvotes: 1