类方法与对象方法
Posted 晴天的故事
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了类方法与对象方法相关的知识,希望对你有一定的参考价值。
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 B = function(){this.getName=function(){}; var b = new B(); Object.defineProperty(b,"Name",{value:"John",writable:true}); B.prototype.getName = function(){return "Parent said:" + this.Name;};
B.prototype.setName = function(value){this.Name = value;}; var A = function(){}; A.prototype= b; var a = new A(); alert(a.Name); // Parent said 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",writerable: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); // Parent said John alert(a.getName()); //Parent said John
a.setName("Keven");
alert(a.getName());//Parent child object said John
What, 最后一条输出没有出来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",writerable:true}); Parent.prototype.getName = function(){return "Parent sard:" + this.Name;}; Parent.getName = fucntion(){return this.Name;}; Parent.prototype.setName = function(value){this.Name = value;}; var A = function(){}; A.prototype= b; var a = new A(); alert(a.Name); // Parent said John alert(a.getName()); //Parent 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",writerable:true}); Parent.prototype.getName = function(){return "Parent sard:" + this.Name;}; Parent.getName = fucntion(){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); // Parent said 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
以上是关于类方法与对象方法的主要内容,如果未能解决你的问题,请参考以下文章