我模仿了一个库,并能够编写以下代码。此代码创建了分配给'c'函数的'a'对象。因此,要调用'a',我必须编写c.a()。
此外,我还向这个'c'对象添加了更多的函数。我想了解这段代码中发生了什么。它看起来不像普通的面向对象编程。这种类型的javascript编程叫什么?
var c = (function(c) {
if (c === undefined) {
c = {};
}
function a() {
alert(1);
}
c.a = a;
return c;
}(c));发布于 2015-01-15 09:56:27
下面是相同的代码,并添加了注释,说明每行都做了什么,以及传递时会发生什么。
//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.https://stackoverflow.com/questions/27960682
复制相似问题