Skip to content Skip to sidebar Skip to footer

Myclass Should Only Be Accessible Via The Namespace

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 sayHel

Solution 1:

The class constructor should accept a single string argument.

varMyClass = function (str) { };

It should also have a function named sayHello that returns the string passed into the constructor.

varMyClass = function (str) {
    this._str = str;
};

MyClass.prototype.sayHello = function () {
    returnthis._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 () {
    returnthis._str;
};

Code should not redefine an existing namespace, but should also function if the namespace is not previously defined.

varMyNamespace = MyNamespace || {};

MyNamespace.MyClass = function (str) {
    this._str = str;
};

MyNamespace.MyClass.prototype.sayHello = function () {
    returnthis._str;
};

Result:

var obj = newMyNamespace.MyClass('foo');
console.log(obj.sayHello()); // foo

Solution 2:

This is probably what you want.

var MyNamespace = {
    MyClass: function (string) {
        returnfunctionsayHello(){
            returnstring;
        }
    }
}

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) {
        returnfunctionsayHello() {
            returnstring;
        }
    }

    console.log(new MyClass('Hello!')());
})()

Solution 3:

functionMyClass() {
    this.MyAttribute = function(string) {
        return string;
    };
}

console.log(newMyClass().MyAttribute('hello'));

Post a Comment for "Myclass Should Only Be Accessible Via The Namespace"