1. 原型与原型链
每个对象都有 __proto__ 属性,但只有函数对象才有 prototype 属性
a.字面量方式
var a = {};
console.log(a.__proto__); //Object {}
console.log(a.__proto__ === a.constructor.prototype); //true
b.构造器方式
var A = function(){};
var a = new A();
console.log(a.__proto__); //A {}
console.log(a.__proto__ === a.constructor.prototype); //true
console.log(a.__proto__ === A.prototype); //true
原型prototype:原型是一个对象,其他对象可以通过它实现属性继承。
原型链__proto__:js里万物皆对象,我们都知道每个对象都有__proto__,所以就会形成一个__proto__的链条,递归访问__proto__,最终为null
var A = function(){};
var a = new A();
console.log(a.__proto__); //A {}(即构造器function A 的原型对象)
console.log(a.__proto__.__proto__); //Object {}(即构造器function Object 的原型对象)
console.log(a.__proto__.__proto__.__proto__); //null
2.JS继承
第一种方式:构造函数继承
function Person (name, age) {
this.name = name;
this.age = age;
this.sayAge = function(){
console.log('hello, my age is ' +this.age);
};
}
Person.prototype.say = function(){
console.log('hello, my name is ' +this.name);
};
function Man(name, age) {
Person.apply(this, arguments);
}
var man1 = new Man('joe', 23);
var man2 = new Man('david');
console.log(man1.name === man2.name);//false
man1.sayAge(); //hello, my age is 23
man1.say(); //say is not a function
评论:不靠谱,原型的方法无法继承
第二种方式:拷贝继承
for(varname in Person.prototype) {
Man1.prototype[name] = Person.prototype[name];
}
评论: 这是拷贝,算不上真正的继承
第三种方式:原型链继承
Obj2.prototype = obj.prototype;
评论: 继承后的属性或方法改变后,被继承的相应也改变了,这是公用,算不上真正的继承。
第四种方式:组合继承
function Person (name, age) {
this.name = name;
this.age = age;
this.sayAge = function(){
console.log('hello, my age is ' +this.age);
};
}
Person.prototype.say = function(){
console.log('hello, my name is ' +this.name);
};
function Man(name, age) {
Person.apply(this, arguments);
}
Man.prototype = new Person();
var man = new Man('joe', 25);
man.sayAge(); //hello, my age is 25
man.say(); //hello, my name is joe
---------------------打印构造函数---------------------------
console.log(Man.prototype.constructor)
ƒ Person (name, age) {
this.name = name;
this.age = age;
this.sayAge = function(){
console.log('hello, my age is ' +this.age);
};
}
评论:看着靠谱了,就有一个小瑕疵,man的constructor 不是Man
第五种方式: 寄生组合继承 常用经典继承方式
function Man(name, age) {
Person.apply(this, arguments);
}
Man.prototype = new Person();//A
Man.prototype.constructor = Man;//b.
评论:最后一种是我们 经常用的,不过多解释了