JavaScript 模块模式 - 使用“return this”怎么样?

发布于 2024-08-30 10:29:21 字数 685 浏览 10 评论 0原文

在阅读了一些有关模块模式的内容之后,我看到了几种返回您想要公开的属性的方法。

最常见的方法之一是在“return”语句中声明公共属性和方法,除了私有属性和方法之外。类似的方式(“揭示”模式)是提供对您想要公开的属性和方法的简单引用。最后,我看到的第三种技术是在模块函数内创建一个新对象,在返回该对象之前向该对象分配新属性。这是一个有趣的想法,但需要创建一个新对象。

所以我在想,为什么不直接使用 this.propertyName 来分配你的公共属性和方法,最后使用 return this 呢?这种方式对我来说似乎更简单,因为您可以使用通常的 varfunction 语法创建私有属性和方法,或者使用 this.propertyName 语法来声明您的公共方法。

这是我建议的方法:

(function() {

var privateMethod = function () {
    alert('This is a private method.');
}

this.publicMethod = function () {
    alert('This is a public method.');
}

return this;

})();

使用上述方法有什么优点/缺点吗?其他人呢?

After doing some reading about the Module Pattern, I've seen a few ways of returning the properties which you want to be public.

One of the most common ways is to declare your public properties and methods right inside of the "return" statement, apart from your private properties and methods. A similar way (the "Revealing" pattern) is to provide simply references to the properties and methods which you want to be public. Lastly, a third technique I saw was to create a new object inside your module function, to which you assign your new properties before returning said object. This was an interesting idea, but requires the creation of a new object.

So I was thinking, why not just use this.propertyName to assign your public properties and methods, and finally use return this at the end? This way seems much simpler to me, as you can create private properties and methods with the usual var or function syntax, or use the this.propertyName syntax to declare your public methods.

Here's the method I'm suggesting:

(function() {

var privateMethod = function () {
    alert('This is a private method.');
}

this.publicMethod = function () {
    alert('This is a public method.');
}

return this;

})();

Are there any pros/cons to using the method above? What about the others?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

像极了他 2024-09-06 10:29:21

您的函数没有对象上下文,因此在本例中 this 引用了全局 window 对象。您分配给 this 的每个属性都会自动污染全局命名空间。

(function() {
    console.log(this == window); // true

    this.publicMethod = function () {
        alert('This is a public method.');
    }

})();

console.log(publicMethod); // function()

您可以显式地向其传递一个对象来告知要使用哪个上下文。

var MYAPP = {};

(function() {
    // 'this' will now refer to 'MYAPP'
    this.publicMethod = function () {
        alert('This is a public method.');
    }
}).call(MYAPP);

console.log(publicMethod); // undefined
console.log(MYAPP.publichMethod); // function()

您可以用其他风格编写:

var MYAPP = (function(my) {
    var my;
    ⋮
    return my;
})(MYAPP);

我们已经到达 讨论了模式。有关更多详细信息,请参阅 Dustin 关于确定匿名函数范围的文章。

Your function has no object context, so this references to the global window object in this case. Every property you assign to this automatically pollutes the global namespace.

(function() {
    console.log(this == window); // true

    this.publicMethod = function () {
        alert('This is a public method.');
    }

})();

console.log(publicMethod); // function()

You can explicitly pass it an object to tell which context to use.

var MYAPP = {};

(function() {
    // 'this' will now refer to 'MYAPP'
    this.publicMethod = function () {
        alert('This is a public method.');
    }
}).call(MYAPP);

console.log(publicMethod); // undefined
console.log(MYAPP.publichMethod); // function()

Which you can write in somewhat other style:

var MYAPP = (function(my) {
    var my;
    ⋮
    return my;
})(MYAPP);

And we arrived to an already discussed pattern. For further details, see Dustin's article on Scoping anonymous functions.

悍妇囚夫 2024-09-06 10:29:21

我建议您将公共属性和方法添加到然后返回的匿名对象中:

var myModule = (function() {
    function privateMethod() { ... }
    function publicMethod() { ... }

    return { publicMethod: publicMethod };
})();

I would recommend the style where you add your public properties and methods to an anonymous object that you then return:

var myModule = (function() {
    function privateMethod() { ... }
    function publicMethod() { ... }

    return { publicMethod: publicMethod };
})();
花开浅夏 2024-09-06 10:29:21

如果您想发布方法,请执行以下操作:

var export = (function() {

var privateMethod = function () {
  alert('This is a private method.');
}
var export = {};

export.publicMethod = function () {
  alert('This is a public method.');
}

return export;

})();

if you want to publish methods, then do something like:

var export = (function() {

var privateMethod = function () {
  alert('This is a private method.');
}
var export = {};

export.publicMethod = function () {
  alert('This is a public method.');
}

return export;

})();
执手闯天涯 2024-09-06 10:29:21

另一种选择是完全避免 this 引用。定义一个创建并返回匿名对象的函数。

function makeThing(someAttribute) {
  var privateVariable = 42;

  function someMethod() {
    return privateVariable;
  }

  return {
    "publicMethodName": someMethod,
    "getAttribute": function() {
      return someAttribute;
    }
  };
}

var thing = makeThing(99);
thing.publicMethodName();
thing.getAttribute();

Another option is to avoid the this reference altogether. Define a function that creates and returns an anonymous object instead.

function makeThing(someAttribute) {
  var privateVariable = 42;

  function someMethod() {
    return privateVariable;
  }

  return {
    "publicMethodName": someMethod,
    "getAttribute": function() {
      return someAttribute;
    }
  };
}

var thing = makeThing(99);
thing.publicMethodName();
thing.getAttribute();
本宫微胖 2024-09-06 10:29:21

揭示模块模式:

var m1 = (function(){ return {method: mthod} })();
var m2 = new function Singleton(){ return {method: mthod} };
var m3 = ({}).prototype = {method: method};
var m4 = ({}).prototype = (function(){ ... })();
var m5 = (function(){}).prototype = {} || (function(){ ... })();

var m6 = (function(extendee){
    return extendee.prototype = {attr3: 'attr3'};
})({currentAttr1: 1, currentAttr2: 2});

此外,如果您需要方法链接:

var m = (function(){}).prototype = (function(){
    var thus = m;  // this
    console.log('m this-------', thus);

    function fn(){
        console.log('fn', thus);
        return thus;
    }
    function f(){
        console.log('f', thus);
        return 'poop';
    }

    return {f: f, fn: fn};
})();

console.log('M:', m, 'm.fn', m.fn(), 'm.fn.f', m.fn().f());

还有很多方法,您也可以让您的模块成为主角。

Revealing Module patterns:

var m1 = (function(){ return {method: mthod} })();
var m2 = new function Singleton(){ return {method: mthod} };
var m3 = ({}).prototype = {method: method};
var m4 = ({}).prototype = (function(){ ... })();
var m5 = (function(){}).prototype = {} || (function(){ ... })();

var m6 = (function(extendee){
    return extendee.prototype = {attr3: 'attr3'};
})({currentAttr1: 1, currentAttr2: 2});

Also, if you need method-chaining:

var m = (function(){}).prototype = (function(){
    var thus = m;  // this
    console.log('m this-------', thus);

    function fn(){
        console.log('fn', thus);
        return thus;
    }
    function f(){
        console.log('f', thus);
        return 'poop';
    }

    return {f: f, fn: fn};
})();

console.log('M:', m, 'm.fn', m.fn(), 'm.fn.f', m.fn().f());

There's also plenty more ways, and you can protagonize your modules as well.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文