依旧是恶补js基础,上代码:
1、定义父类及父类方法
function Animal(){ this.name = "动物"; } Animal.prototype.eat = function(food){ alert('eat ' + food); }
2、定义子类
function Ferret(){ this.name = "雪貂";
//this.type = "leixing";//此处,如果定义了type,会覆盖下面prototype.type的“domestic”
//说明一个机制,调用Ferret().type的时候,先寻找对象自有属性,再查找原型链内属性
}
3、原型链继承核心
function fn(){ //中间函数,防止每次创建对象都要new }
//父类的属性与方法通过prototype传递给中间函数 fn.prototype = Animal.prototype;
//中间函数的实例将父类的属性与方法传递给子类的prototype Ferret.prototype = new fn();
4、扩展子类
//为所有Ferret实例定义type属性 Ferret.prototype.type = "domestic"; Ferret.prototype.eat = function(food){ //子类执行父类的方法 Animal.prototype.eat.call(this,food); //子类的扩展逻辑 alert(this.type + ' eat ' + food); }
5、测试继承结果
var animal = new Animal(); var ferret = new Ferret();
animal instanceof Animal // true
animal instanceof Ferret // false
ferret instanceof Ferret // true
ferret instanceof Animal // true 此处,子类是父类的实例为true,说明继承成功~
ferret.eat('meat');//1、alert(eat meat); 2、alert(domestic eat meat);
以下是一些啰嗦:
var a = { a: 'b', c: 'd' }; function a1(){ this.a = 'b'; this.c = 'd'; }
a instanceof Object // true
a1 instanceof Object // true
由此可以看出,a与a1均属于对象,那么,有什么区别呢
a.prototype == undifiend // true
a1.prototype == undefined // false
typeof a == "object" // true
typeof a1 == "function" // true
Object.keys(a) // ["a", "c"]
Object.keys(a1) // []
a仅仅是一个单纯的key&value,没有构造函数,属于【引用类型】
而a1则有prototype,可以实现继承,通过Object.keys()可以看出,a1身为一个Object,不存在key&value,属于【值类型】
V8中的继承:
function Animal(){} function Ferret(){} Ferret.prototype.__proto__ = Animal.prototype// 父类将属性传递给子类