Nothing to say. Three examples
Patients with a
Uncontrolled value transfer
class A {
constructor(n) {
this.n = n
}
then(fn){
fn(this.n)
}
}
new A(3).then(data= >{
console.log(data)/ / 3
})
Copy the code
Example 2
The control function is in the parameters
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
})
Copy the code
Example 3
The control function is called in class initialization
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
})
Copy the code
Cases of four
Constructor version of example 3
The control function is called in constructor initialization
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
})
Copy the code
conclusion
Example 1: An instance initializes, passing in a value whose method can be read later
Example 2: Instance initialization, passing in a value, and controlling the final value with a callback function whose methods can be read later
Example 3: Instance initialization, the purpose of which is to pass in a value, reduces the argument to one, relative to Example 2
Harvest:
- If you change a parameter, the argument does not change. In the case of reading, the effect of writing is directional
- Practice makes perfect