Created
March 9, 2017 13:33
-
-
Save blackmiaool/39c5b2b4672e83f27b383009ca2a2c1e to your computer and use it in GitHub Desktop.
invoke parent method
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class A { | |
componentWillMount() { // base first | |
console.warn("A1"); | |
} | |
componentDidMount() { | |
console.warn("A2"); | |
} | |
componentWillUnmount() { | |
console.warn("A3"); | |
} | |
} | |
class B extends A { | |
componentWillMount() { // base first | |
console.warn("B1"); | |
} | |
componentWillUnmount() { | |
console.warn("B3"); | |
} | |
} | |
// | |
// class C extends B { | |
// componentWillMount() { // base first | |
// console.warn("C1"); | |
// } | |
// componentDidMount() { | |
// console.warn("C2"); | |
// } | |
// componentWillUnmount() { | |
// console.warn("C3"); | |
// } | |
// } | |
console.dir(B) | |
function annotation(target) { | |
function execute(key, baseFirst) { | |
let current = target; | |
let preFunc; | |
if (current.prototype.hasOwnProperty(key)) { | |
preFunc = current.prototype[key]; | |
} | |
target.prototype[key] = function() { | |
const that = this; | |
const queue = []; | |
if (preFunc) { | |
if (baseFirst) { | |
queue.push(preFunc); | |
} else { | |
preFunc.call(that); | |
} | |
} | |
current = Object.getPrototypeOf(current.prototype).constructor; | |
while (current !== Object.getPrototypeOf(A.prototype).constructor) { | |
const func = current.prototype[key]; | |
if (func && current.prototype.hasOwnProperty(key)) { | |
if (baseFirst) { | |
queue.push(func); | |
} else { | |
func.call(that); | |
} | |
} | |
if (Object.getPrototypeOf(current.prototype)) { | |
current = Object.getPrototypeOf(current.prototype).constructor; | |
} else { | |
break; | |
} | |
} | |
if (baseFirst && queue.length) { | |
for (let i = queue.length - 1; i >= 0; i--) { | |
queue[i].call(that); | |
} | |
} | |
}; | |
} | |
execute("componentWillMount", true); | |
execute("componentDidMount", false); | |
execute("componentWillUnmount", false); | |
} | |
annotation(B); | |
const page = new B(); | |
page.componentWillMount(); | |
page.componentDidMount(); | |
page.componentWillUnmount(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment