JS面向对象
1、最简单的面向对象
index.html代码
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta charset="UTF-8"> 5 <title>uvi</title> 6 <script src="myjs2.js"></script> 7 </head> 8 <body> 9 10 11 </body> 12 </html>
js代码:
1 function People(){ 2 3 } 4 People.prototype.say = function(){ 5 alert("hello"); 6 } 7 8 function Student(){ 9 10 } 11 Student.prototype = new People();//继承People 12 var s = new Student(); 13 s.say();
运行后,成功弹出对话框"hello"
2、其他特性,看注释
1 function People(){ 2 3 } 4 People.prototype.say = function(){ 5 alert("hello"); 6 } 7 8 function Student(){ 9 10 } 11 Student.prototype = new People();//继承People 12 var superSsay = Student.prototype.say; 13 Student.prototype.say=function(){//定义自身类的方法时,复写父类的方法时,调用的是自身的方法 14 superSsay.call(this);//这是调用父类的say方法 15 alert("stu-hello"); 16 } 17 var s = new Student(); 18 s.say();
3、构造函数参数
1 function People(name){//指定参数 2 this._name = name; 3 } 4 People.prototype.say = function(){ 5 alert("peo-hello"+this._name); 6 } 7 8 function Student(name){//父类指定参数,子类也要指定参数 9 this._name = name; 10 } 11 Student.prototype = new People();//继承People 12 var superSsay = Student.prototype.say; 13 Student.prototype.say=function(){//定义自身类的方法时,复写父类的方法时,调用的是自身的方法 14 superSsay.call(this);//这是调用父类的say方法 15 alert("stu-hello"+this._name); 16 } 17 var s = new Student("uvi");//实例化要传递参数 18 s.say();
4、实现封装
1 (function(){//封装信息 2 var n = "iwen"; //此时只能在内部访问到,实现封装 3 function People(name){ 4 this._name = name; 5 } 6 People.prototype.say = function(){ 7 alert("peo-hello"+this._name+n); 8 } 9 10 window.People = People;//实现对外访问的接口 11 }()); 12 13 (function(){ 14 function Student(name){//父类指定参数,子类也要指定参数 15 this._name = name; 16 } 17 Student.prototype = new People();//继承People 18 var superSsay = Student.prototype.say; 19 Student.prototype.say=function(){//定义自身类的方法时,复写父类的方法时,调用的是自身的方法 20 superSsay.call(this);//这是调用父类的say方法 21 alert("stu-hello"+this._name); 22 23 } 24 window.Student = Student;//实现对外访问的接口 25 }()); 26 var s = new Student("uvi");//实例化要传递参数 27 s.say();
5、另一种方法实现面向对象(对象传递)
1 function Person(name){ 2 var _this = {} //空对象 3 _this._name = name; 4 _this.sayHello = function(){ 5 alert("P-hello world"+_this._name); 6 } 7 return _this; 8 } 9 10 function Teacher(name){ 11 var _this = Person(name);//通过继承,对象的传递 12 var superSay = _this.sayHello; 13 _this.sayHello = function(){//复写父类的方法 14 superSay.call(_this); 15 alert("THello"+_this._name); 16 } 17 return _this; 18 } 19 var t = Teacher("asd"); 20 t.sayHello();
1 (function(){ 2 var n = "ime"; 3 function Person(name){ 4 var _this = {} //空对象 5 _this._name = name; 6 _this.sayHello = function(){ 7 alert("P-hello world"+_this._name+n); 8 } 9 return _this; 10 } 11 window.Person = Person;//赋值给窗口执行 12 }()); 13 14 function Teacher(name){ 15 var _this = Person(name);//通过继承,对象的传递 16 var superSay = _this.sayHello; 17 _this.sayHello = function(){//复写父类的方法 18 superSay.call(_this); 19 alert("THello"+_this._name); 20 } 21 return _this; 22 } 23 var t = Teacher("asd"); 24 t.sayHello();