Created
May 29, 2016 13:36
-
-
Save black-black-cat/8fdf4d1b1e5def95f4834408566a07dd to your computer and use it in GitHub Desktop.
原型继承
This file contains hidden or 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
/** | |
* @param {Function} subType | |
* @param {Function} superType | |
*/ | |
function inheritPrototype(subType, superType) { | |
// 以一个空函数作为中介,保证不把父类构造器中的属性带进原型链 | |
function F() {} | |
// 把F的prototype指向父类的prototype,修改整个prototype而不是部分prototype | |
F.prototype = superType.prototype; | |
// new F()完成两件事情,1. 执行F构造函数,为空;2. 执行F的prototype的内存分配,这里就是父类,也就是Person的getAge方法 | |
// 所以这里是继承了父类的getAge()方法,赋值给了proto | |
var proto = new F(); | |
// proto的构造函数显示指定为子类(由于上面重写了F的prototype,故而构造函数也变化了) | |
proto.constructor = subType; | |
subType.prototype = proto; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment