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
3 Answers 3
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/
2 Comments
__proto__ works because objects do not have a prototype, functions do. However __proto__ is not standard and won't work across browsers, that is what getPrototypeOf is for. But the second method really is much cleaner.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();
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
undefinedortypeof Sample === 'undefined'not"undefined".Sample == "undefined"is not going to test if it is undefined, it is going to test whetherSampleequals the string "undefined."Sample == undefinedbut then again the whole undefined is unnecessary, that's what!Sampleis testing for anyway.