最近有个小伙伴遇到了个面试题,在PHP
实现Db::table()->where()->query()
这种链式操作是怎么实现的。我一时之间突然还想不出来。看了下TP
的源码给大家分享一下
有道了一哈链式这个单词
chained
class chainedClass() {
public function a() {
echo '调用了方法a';
return $this;
}
public function b() {
echo '调用了方法b';
return $this;
}
//function ...
}
//调用
$chained = new chainedClass();
//调用ab的顺序可以无序
$chained->a()->b();
言归正传,我们看到JavaScript
中也有很多这样的操作,比如JQuery
啊,什么什么的,我们自己封装的时候也想用一个链式操作咋办呢,来呗,各位客观来看看下面呗
- 写法一
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
</head>
<body>
<script>
class test {
constructor(name, age) {
this.name = name
this.age = age
}
a () {
console.log('name', this.name)
return this
}
b () {
console.log('age:', this.age)
return this
}
}
let a = new test('wenqian:', 24)
a.a().b()
</script>
</body>
</html>
- 写法2(兼容
ES6
以前的浏览器)
let testListFun = function(){
const a = function() {
console.log(111)
return this
}
const b = function() {
console.log(2)
return this
}
return {
a,
b
}
}
testListFun().a().b()
至于在需要在方法之间实现这种链式操作,就要学会call
、apply
、bind
的写法,剩下的交给各位同学们自己去理解把!
@QQ: 843462167