js函数式编程确实比很多强语言使用灵活得多,今天抽了点时间玩下类与对象方法调用优先级别,顺便回顾下继承
暂时把原型引用写成继承
先看看简单的两个继承
var Parent = function(){}; var b = new Parent(); Object.defineProperty(b,"Name",{value:"John",writable:true}); var A = function(){}; A.prototype= b; var a = new Child(); alert(a.Name); //John
给父类原型加上类方法
var Parent = function(){}; var b = new Parent(); Object.defineProperty(b,"Name",{value:"John",writable:true}); Parent.prototype.getName = function(){return "Parent said:" + this.Name;}; Parent.prototype.setName = function(value){this.Name = value;}; var A = function(){}; A.prototype= b; var a = new A(); alert(a.Name); // John alert(a.getName()); //Parent said John a.setName("Keven"); alert(a.getName());//Parent said Keven
子类继承并使用了父类原型的方法和属性, 也能通过父类提供的方法修改继承的属性值
var Parent = function(){this.getName=function(){return "Parent child object said:"+this.Name};}; var b = new Parent(); Object.defineProperty(b,"Name",{value:"John",writable:true}); Parent.prototype.getName = function(){return "Parent sard:" + this.Name;}; Parent.prototype.setName = function(value){this.Name = value;}; var A = function(){}; A.prototype= b; var a = new A(); alert(a.Name); // John alert(a.getName()); //Parent child object said John a.setName("Keven"); alert(a.getName());//Parent child object said Keven
此处可以看出对象方法优先于原型方法调用,当对象方法没有找到时会向上层原型查找
再来看看类方法,Parent类加上getName方法
var Parent = function(){this.getName=function(){return "Parent child object said:"+this.Name};}; var b = new Parent(); Object.defineProperty(b,"Name",{value:"John",writable:true}); Parent.prototype.getName = function(){return "Parent sard:" + this.Name;}; Parent.getName = function(){return this.Name;}; Parent.prototype.setName = function(value){this.Name = value;}; var A = function(){}; A.prototype= b; var a = new A(); alert(a.Name); // John alert(a.getName()); //Parent child object said John a.setName("Keven"); alert(a.getName());//Parent child object said Keven alert(A.prototype.Name); //John alert(A.getName()) // type error, undefine is not a function
最后一条报错,A并没有继承Parent的getName方法,此处可以理解Parent.getName为静态方法,不会被子类继承
var Parent = function(){this.getName=function(){return "Parent child object said:"+this.Name};}; var b = new Parent(); Object.defineProperty(b,"Name",{value:"John",writable:true}); Parent.prototype.getName = function(){return "Parent sard:" + this.Name;}; Parent.getName = function(){return this.Name;}; Parent.prototype.setName = function(value){this.Name = value;}; var A = function(){this.getName=function(){return "A object said:"+this.Name};}; A.prototype= b; var a = new A(); alert(a.Name); // John a.setName("Keven"); alert(a.getName());//A object said Keven alert(A.prototype.Name); //John alert(A.getName()) // type error, undefine is not a function
从第二个alert可以看出,当子类有同名方法时优先调用子类对象上的方法getName,总结下来方法查找的顺序为:子对象方法>父对象方法>父原型方法,一句话为越近越亲,层层往上
以上简单试验了一下js里的原型方法,类方法,和对象方法在继承之后的执行顺序,下节一起探讨下原型链模型