JS-回调函数的"演变"

163 阅读1分钟

没啥说的,三个例子

例一

不加控制传值

class A {
    constructor(n) {
        this.n = n
    }
    then(fn){
        fn(this.n)
    }
}
new A(3).then(data=>{
    console.log(data)//3
})

例二

控制函数在参数中

class A {
    constructor(excu, n) {
        this.n = excu(n)
    }
    then(fn) {
        fn(this.n)
    }
}
new A(function (inner) {
    if (inner > 10) {
        inner = 10
    } else if (inner < 5) {
        inner = 5
    }
    console.log(inner)
    return inner

}, 11).then((data) => {
    console.log(data)//10
})

例三

控制函数在类初始化中调用

class A {
    constructor(excu, n) {
        this.n = 0
        let fn = inner=>{
            if (inner > 10) {
                this.n = 10
            } else if (inner < 5) {
                this.n = 5
            } else {
                this.n = inner
            }
        };
        excu(fn)
    }
    then(fn) {
        fn(this.n)
    }
}
new A( (inner)=> {
    inner(11)
}).then((data) => {
    console.log(data)//10
})

例四

例三的构造函数版本

控制函数在构造函数初始化中调用

function B(excu){
    this.n = 0
    let fn = inner=>{
        if (inner > 10) {
            this.n = 10
        } else if (inner < 5) {
            this.n = 5
        }else{
            this.n = inner
        }
    }
    excu(fn)
}
B.prototype.then = function(fn){
    fn(this.n)
}

new B((inner) => {
    inner(16)
}).then((data) => {
    console.log(data)//10
})

总结

例一:实例初始化,传一个值进去,它的方法可以后续读操作

例二:实例初始化,传一个值进去,并用一个回调函数控制最终的值,它的方法可以后续读操作

例三:实例初始化,目的是传一个值进去,相对于例二,它将参数减少到一个

收获:

  1. 改变形参,实参是不会改变的,论读取,双向都可以,写的影响是有方向性的
  2. 熟能生巧