Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save blackmiaool/39c5b2b4672e83f27b383009ca2a2c1e to your computer and use it in GitHub Desktop.
Save blackmiaool/39c5b2b4672e83f27b383009ca2a2c1e to your computer and use it in GitHub Desktop.
invoke parent method
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