MyClass should only be accessible via the namespac

2020-05-09 17:23发布

问题:

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!

回答1:

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


回答2:

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!')());
})()


回答3:

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

console.log(new MyClass().MyAttribute('hello'));