我想用下面的代码来执行我的add function
。但我没有得到正确的语法。
我已经尝试x.add(3,4)
和x().add(3,4)
,但不起作用。请让我知道我错了。
<html>
<body>
<p>
After a function has been stored in a variable,
the variable can be used as a function:
</p>
<p id="demo">
hello
</p>
<script>
var x = function () {
var add = function(a, b) { return a + b };
var mul = function(a, b) { return a * b };
}();
document.getElementById("demo").innerHTML = x.add(3,4);
</script>
</body>
</html>
看来你想x
为对象。对于正确的语法是
var x = {
add: function(a,b){return a + b},
mul: function(a,b){return a * b},
};
或者,如果你坚持使用IIFE(因为你比你已经证明,范围做更多的事情),那么你会怎么做
var x = (function () {
function add(a,b){return a + b}
function mul(a,b){return a * b}
return {add, mul};
}());
其它功能中定义的函数都没有自动提供给外码。其默认是存在的时间相同任何其他局部变量,可进行垃圾回收时,外部函数执行完毕。
为了保持他们身边,你需要指定要如何使其可用。对于一个选择是回报他们,增加了结构来保持他们两个:
var x = function () {
return {
add: function(a,b){return a + b},
mul: function(a,b){return a * b},
};
}();
不过,至少到目前为止,外部功能不是绝对必要的,并可能将其删除:
var x = {
add: function(a,b){return a + b},
mul: function(a,b){return a * b},
};
见内嵌下面的评论:
// You can set the function up as a "constructor function",
// meaning that an object instance will be constructed from the
// invocation of the function. Standard convention is to use
// PascalCase for constructor function names:
function X() {
// Later, when an instance of this object is made,
// members of the object can be gotten by identifying
// them as going along with "this" object instance.
// There is more to know about this (ie. properties are
// created as I'm showing here, but methods are often
// added to the function's prototoype).
this.add = function(a,b){return a + b};
this.mul = function(a,b){return a * b};
}
// Use the function to construct an object instance
let instance = new X();
// Then, use that instance and its associated members.
// FYI: Don't use .innerHTML when you aren't getting/setting
// any HTML. Use .textContent for raw text.
document.getElementById("demo").textContent = "Add: " + instance.add(3,4);
document.getElementById("demo").textContent += " | Multiply: " + instance.mul(3,4);
<p>After a function has been stored in a variable,
the variable can be used as a function:</p>
<p id="demo">hello</p>
你在做什么这里是定义一个函数命名x
,并且限定功能,名为add
和mul
内的两个变量。由于的JavaScript如下,当谈到item scope(尤其是在功能方面,请参见Function Scope)的规则,这些变量是不可访问的功能之外。要访问它们,你需要具备的功能return
定义它们的对象:
var x = function() {
var add = function(a,b){return a + b};
var mul = function(a,b){return a * b};
return {
add: add,
mul: mul
};
}
这些现在可以通过调用函数,该函数将返回这两个值进行访问:
var y = x();
document.getElementById("demo").innerHTML = y.add(3,4);
在端功能,如果你想声明public
变量constuctor
使用this
。并确保把new
创建您new
的constructor
实例
var x = new function () {
this.add = function(a,b){return a + b};
this.mul = function(a,b){return a * b};
};
console.log(x.add(1,3));
console.log(x.mul(5,3));