MyClass should only be accessible via the namespac

2020-05-09 17:43发布

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!

3条回答
啃猪蹄的小仙女
2楼-- · 2020-05-09 18:14

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楼-- · 2020-05-09 18:17

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
查看更多
你好瞎i
4楼-- · 2020-05-09 18:21
function MyClass() {
    this.MyAttribute = function(string) {
        return string;
    };
}

console.log(new MyClass().MyAttribute('hello'));
查看更多
登录 后发表回答