MyClass应该只能通过命名空间访问 [英] MyClass should only be accessible via the namespace

查看:215
本文介绍了MyClass应该只能通过命名空间访问的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在命名空间MyNamespace中定义一个名为MyClass的类。类构造函数应该接受单个字符串参数。它还应该有一个名为sayHello的函数,它返回传递给构造函数的字符串。

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.

有趣的部分是MyClass只能通过命名空间访问,额外的全局变量。代码不应重新定义现有的命名空间,但如果命名空间未预先定义,也应该函数。

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.

我在这里做什么?

var MyNamespace = {
  MyClass: (function(string){
    function sayHello(){
      return string;
    }
  })()
    console.log(new MyNamespace.MyClass('Hello!'));
}

链接到小提琴: http://jsfiddle.net/marcusdei/wqvc0k1j/8/

ps这不是家庭作业,我正在学习JS为我的职业生涯。
谢谢!

p.s.This is not homework, I'm learning JS for my career. Thanks!

推荐答案


类构造函数应该接受单个字符串参数。 p>

The class constructor should accept a single string argument.



var MyClass = function (str) { };




它还应该有一个名为 sayHello ,返回传递给构造函数的字符串。

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;
};




有趣的部分是 MyClass 应该只能通过命名空间访问,不应该定义任何额外的全局变量。

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;
};

结果:

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

这篇关于MyClass应该只能通过命名空间访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆