JavaScript 继承
1.原型链继承(会继承原型链上的全部属性和方法)
function Grand() {}
Grand.prototype.money = "10000";
var grand = new Grand();
function Father() {}
Father.prototype = grand;
var father = new Father();
function Son() {}
Son.prototype = father;
var son = new Son;
2.构造函数继承 (B构造函数的属性完全包括A构造函数时使用)
function A(name,age,sex) {
this.name = name;
this.age = age;
this.sex = sex;
}
function B(name,age,sex,id) {
Teather.call(this,name,age,sex);
// Teather.apply(this,[name,age,sex]);
this.id = id;
}
var B= new B("小明",20,"男","A0001");
3.共享原型(不能随便更改原型 A改 B也改,B改 A也改)
A.prototype.color = "red";
function A() {
}
var a = new A;
function B() {
}
B.prototype = a;
var b = new B();
4.圣杯模式
Father.prototype = {
name:"wang",
}
function Father() {
}
function Son() {
}
var inherit = (function () {
var A = function () {}
return function (Target,Origin) {
A.prototype = Origin.prototype;
Target.prototype = new A();
Target.prototype.constructor = Target;
Target.prototype.uber = Origin.prototype;
}
})();
inherit(Son,Father);
var son = new Son();//必须写在 inherit()函数的调用之后 如果在之前 new 的时候 father的原型与son的原型不相等
var father = new Father();

浙公网安备 33010602011771号