继承
1、传统形式----->原型链
(过多的继承了没有用的属性)
2、借用构造函数----->call/apply
(不能继承,借用构造函数的原理,每次构造函数都要多走一个函数,浪费效率)
3、共享原型
(不能随便改动自己的原型)
4、最终模式
1、原型/原型链
1, 原型是function对象的一个属性,他定义了构造函数生产出对象的公共祖先,
通过该构造函数产生的对象可以继承该原型的属性和方法,原型也是对象.
2,利用原型的特点,可以提取公共属性
原型链
2、借助构造函数
-
改变this指向
-
传参列表不一样(apply需传一个arguments)
2.5混合模式(共享原型+apply/call)
Person.prototype.showName = function() {
console.log(this.name);
}
Person.prototype.showJob = function() {
console.log(this.job);
}function Person(name, age) {
this.name = name;
this.age = age;
}
function Student(name, age, job) {
Person.apply(this, arguments);
this.job = job;
}// for (var i in Person.prototype) {
Student.prototype = Person.prototype;
// }var stu = new Student('tom', 18, 'stu');
stu.showName()
stu.showJob();
console.log(stu.age); //18
3、共享原型
//共享原型--1
Father.prototype.lastName = "wang";
function Father(){
}
function Son(){
}
Son.prototype = Father.prototype; //两者关联起来
var son = new Son();
var father = new Father();
console.log(son.lastName);
console.log(father.lastName);
共享原型 (inherit)存在弊端,Son不能拥有自己独立的原型,
Father.prototype.lastName = "wang";
function Father(){ }
function Son(){ }
function inherit(Target, Origin){
Target.prototype = Origin.prototype;
}
inherit(Son, Father);
Son.prototype.sex = "male"; //不是自己独立拥有的
var son = new Son();
var father = new Father(); //father.sex = "male"
Son不能拥有自己独立的原型,所以调整如下,创建中间层Cur构造函数(封装inherit)
son.__proto__ ---> new F().__proto__ ---> Father.prototype(使son.constructor属于自己)
function inherit(Target, Origin){
function Cur(){}
Cur.prototype = Origin.prototype;
Target.prototype = new Cur();
Target.prototype.constructor = Target; //son的constructor属于自己
Target.prototype.uber = Origin.prototype; //查看正真继承谁:超类(可有可无)
}
Father.prototype.lastName = "wang";
function Father(){}
function Son(){}
inherit(Son, Father);
var son = new Son();
var father = new Father();
4、最终模式
封装inherit让其立即执行:
var inherit = (function() {
var Cur = function() {}
return function(Target, Origin) {
Cur.prototype = Origin.prototype;
Target.prototype = new Cur();
Target.prototype.constructor = Target;
Target.prototype.uber = Origin.prototype;
}
}())
私有化变量
function Wang(name, wife) {
var xwife = 'tom';
this.name = name;
this.wife = wife;
this.dvorce = function() {
this.wife = xwife;
}
this.changeXwife = function(target) {
xwife = target;
}
this.sayXwife = function() {
console.log(xwife);
}
}
var wang = new Wang('wang', 'jack');