首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >这个代码构造包装了库的各个部分,它有什么用处?

这个代码构造包装了库的各个部分,它有什么用处?
EN

Stack Overflow用户
提问于 2015-01-15 09:48:30
回答 6查看 4.1K关注 0票数 39

我模仿了一个库,并能够编写以下代码。此代码创建了分配给'c'函数的'a'对象。因此,要调用'a',我必须编写c.a()

此外,我还向这个'c'对象添加了更多的函数。我想了解这段代码中发生了什么。它看起来不像普通的面向对象编程。这种类型的javascript编程叫什么?

代码语言:javascript
运行
复制
var c = (function(c) {
    if (c === undefined) {
        c = {};
    }

    function a() {
        alert(1);
    }
    c.a = a;
    return c;
}(c));
EN

Stack Overflow用户

发布于 2015-01-15 09:56:27

下面是相同的代码,并添加了注释,说明每行都做了什么,以及传递时会发生什么。

代码语言:javascript
运行
复制
//Here, we're defining a function that will return an object.
//its only parameter is named 'c'
//this is confusing, since the parameter has the same name as the global definition of the function.

//the var c definition is the global definition. the function parameter is not.
//so every reference to anything named 'c' inside the function definition is local. 
var c = (function(c) 
{
  //if c (the c we passed as a parameter) is not yet defined
  if (c === undefined) {
    //define c as an object
    c = {};
  }

  //define a function
  function a() {
    alert(1);
  }
  //attach it to the object
  c.a = a;

  //return the object
  return c;
}(c)); // call the constructor we just defined, using the global definition of `c`.
       // the first time we pass this point, c as a variable is still undefined.
票数 36
EN
查看全部 6 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/27960682

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档