详解JS面向对象编程

这篇文章主要为大家介绍了js面向对象编程,感兴趣的小伙伴们可以参考一下

因为JavaScript是基于原型(prototype)的,没有类的概念(ES6有了,这个暂且不谈),我们能接触到的都是对象,真正做到了一切皆为对象

所以我们再说对象就有些模糊了,很多同学会搞混类型的对象和对象本身这个概念,我们在接下来的术语中不提对象,我们使用和Java类似的方式,方便理解

方式一

类(函数模拟)

 function Person(name,id){ //实例变量可以被继承 this.name = name; //私有变量无法被继承 var id = id; //私有函数无法被继承 function speak(){ alert("person1"); } } //静态变量,无法被继承 Person.age = 18; //公有函数可以被继承 Person.prototype.say = function(){ alert("person2"); } 

继承,并调用父类方法

 function Person(name,id){ //实例变量可以被继承 this.name = name; //私有变量无法被继承 var id = id; //私有函数无法被继承 function speak(){ alert("person1"); } } //静态变量,无法被继承 Person.age = 18; //公有静态成员可被继承 Person.prototype.sex = "男"; //公有静态函数可以被继承 Person.prototype.say = function(){ alert("person2"); } //创建子类 function Student(){ } //继承person Student.prototype = new Person("iwen",1); //修改因继承导致的constructor变化 Student.prototype.constructor = Student; var s = new Student(); alert(s.name);//iwen alert(s instanceof Person);//true s.say();//person2 

继承,复写父类方法且实现super()

 function Person(name,id){ //实例变量可以被继承 this.name = name; //私有变量无法被继承 var id = id; //私有函数无法被继承 function speak(){ alert("person1"); } } //静态变量,无法被继承 Person.age = 18; //公有静态成员可被继承 Person.prototype.sex = "男"; //公有静态函数可以被继承 Person.prototype.say = function(){ alert("person2"); } //创建子类 function Student(){ } //继承person Student.prototype = new Person("iwen",1); //修改因继承导致的constructor变化 Student.prototype.constructor = Student; //保存父类的引用 var superPerson = Student.prototype.say; //复写父类的方法 Student.prototype.say = function(){ //调用父类的方法 superPerson.call(this); alert("Student"); } //创建实例测试 var s = new Student(); alert(s instanceof Person);//true s.say();//person2 student 

继承的封装函数

 function extend(Child, Parent) {     var F = function(){};     F.prototype = Parent.prototype;     Child.prototype = new F();     Child.prototype.constructor = Child;     Child.uber = Parent.prototype;   } 

uber意思是为子对象设一个uber属性,这个属性直接指向父对象的prototype属性。(uber是一个德语词,意思是”向上”、”上一层”。)这等于在子对象上打开一条通道,可以直接调用父对象的方法。这一行放在这里,只是为了实现继承的完备性,纯属备用性质。

方式二

相当于拷贝,通过定义的_this对象来承载想要被继承的对象,这样的话通过传递_this就可以实现继承,比上面那种好理解些

 //创建父类 function Person(name,id){ //创建一个对象来承载父类所有公有东西 //也就是说_this承载的对象才会被传递给子类 var _this = {}; _this.name = name; //这样的是不会传递下去的 this.id = id; //承载方法 _this.say = function(){ alert("Person"); } //返回_this对象 return _this; } //子类 function Student(){ //获取person的_this对象,从而模仿继承 var _this = Person("iwne",1); //保存父类的_this引用 var superPerson = _this.say; //复写父类的方法 _this.say = function(){ //执行父类的say superPerson.call(_this); alert("Student"); } return _this; } var s = new Student(); s.say(); 

希望对大家学习javascript程序设计有所帮助。

以上就是详解JS面向对象编程的详细内容,更多请关注0133技术站其它相关文章!

赞(0) 打赏
未经允许不得转载:0133技术站首页 » JavaScript 教程