I'm trying to define a class named MyClass inside a namespace MyNamespace. The class constructor should accept a single string argument. It should also have a function named sayHello that returns the string passed into the constructor.
The interesting part is that MyClass should only be accessible via the namespace and should not define any extra global variables. Code should not redefine an existing namespace, but should also function if the namespace is not previously defined.
What am I doing wrong here?
var MyNamespace = {
MyClass: (function(string){
function sayHello(){
return string;
}
})()
console.log(new MyNamespace.MyClass('Hello!'));
}
And the link to the fiddle: http://jsfiddle.net/marcusdei/wqvc0k1j/8/
p.s.This is not homework, I'm learning JS for my career.
Thanks!
The class constructor should accept a single string argument.
var MyClass = function (str) { };
It should also have a function named sayHello
that returns the string passed into the constructor.
var MyClass = function (str) {
this._str = str;
};
MyClass.prototype.sayHello = function () {
return this._str;
};
The interesting part is that MyClass
should only be accessible via the namespace and should not define any extra global variables.
MyNamespace.MyClass = function (str) {
this._str = str;
};
MyNamespace.MyClass.prototype.sayHello = function () {
return this._str;
};
Code should not redefine an existing namespace, but should also function if the namespace is not previously defined.
var MyNamespace = MyNamespace || {};
MyNamespace.MyClass = function (str) {
this._str = str;
};
MyNamespace.MyClass.prototype.sayHello = function () {
return this._str;
};
Result:
var obj = new MyNamespace.MyClass('foo');
console.log(obj.sayHello()); // foo
This is probably what you want.
var MyNamespace = {
MyClass: function (string) {
return function sayHello(){
return string;
}
}
}
console.log(new MyNamespace.MyClass('Hello!')());
If you are looking for something like a private member you'd do
var MyNamespace = (function(){
var MyClass = function (string) {
return function sayHello() {
return string;
}
}
console.log(new MyClass('Hello!')());
})()
function MyClass() {
this.MyAttribute = function(string) {
return string;
};
}
console.log(new MyClass().MyAttribute('hello'));