什么是 JavaScript 中的函数链式调用?
函数链式调用
函数链式调用是指使用点表示法将多个函数组合在一行代码中。这种链式调用使代码更简洁,并提高性能。这里我们将学习使用普通对象进行函数链式调用。
a) 没有函数链式调用
在下面的示例中,创建了一个对象 'obj',并使用关键字'this'创建了一个名为 'i' 的公共属性,并将其初始值设置为 0。之后,在同一个对象 'obj' 中创建了名为 add()、subtract() 和 print() 的用户自定义函数。现在,对象 "obj" 将充当类的角色(其属性可以被其他对象共享)。
现在,使用关键字 'new' 创建了另一个名为 'x' 的(用户自定义)对象,并使其能够访问对象 "obj" 的属性。由于在 "obj" 中声明的函数(例如 add()、subtract() 和 print())没有返回值,因此函数链式调用不可行,输出显示为undefined,而单独(非链式)调用这些函数将输出 3(用户提供的 '5-2')。
示例
<html>
<body>
<script>
var obj = function(){
this.i = 0;
this.add = function(i){
this.i += i;
};
this.subtract = function(i){
this.i -= i;
};
this.print = function(){
document.write(this.i);
document.write("</br>");
document.write(x.add(3)); // returns undefined
}
}
var x = new obj();
x.add(5);
x.subtract(2);
x.print(); // 5-2 = 3 so prints 3.
x.add(5).subtract(2).print(); // function chaining is not possible so undefined
</script>
</body>
</html>输出
3 undefined
b) 使用函数链式调用
在下面的示例中,考虑上述示例场景,使用用户自定义的 "return this" 语句,返回 add() 和 subtract() 等函数,从而实现函数链式调用,最终输出 3。
示例
<html>
<body>
<script>
var obj = function(){
this.i = 0;
this.add = function(i){
this.i += i;
return this;
};
this.subtract = function(i){
this.i -= i;
return this;
};
this.print = function(){
document.write(this.i);
}
}
var x = new obj();
x.add(5).subtract(2).print();
</script>
</body>
</html>输出
3
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP