JavaScript笔记-面向对象编程
JavaScipt不区分类和实例,所有的对象都是由一个已有实例(原型 )来创建的。
直接看class 继承吧,前面老语法又难又没用。
创建对象
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 <!DOCTYPE html > <html lang ="en" > <head > <meta charset ="UTF-8" > <title > 面向对象编程</title > </head > <body > <script > var me={ name:'Sang' , age:20, welcome:function ( ) { console .log(this .name+'你好!' ) } }; var you=Object .create(me); you.name='Wang' ; you.welcome(); function Man (height ) { this .height=height; this .speak=function ( ) { console .log(`I am a ${this .height} cm tall man` ); } } var superMan=new Man('250' ); superMan.speak(); console .log(superMan.constructor===Man); console .log(Man.prototype.constructor===Man); console .log(superMan.constructor===Man.prototype.constructor); console .log(superMan instanceof Man); console .log(Man.prototype); console .log(Object .prototype); console .log(Object .getPrototypeOf(superMan)===Man.prototype); function Student (name ) { this .name=name; } Student.prototype.hello=function ( ) { alert('Hello, ' ,this .name+'!' ); }; var xiaohong=new Student('xiaohong' ); var xiaoming=new Student('xiaoming' ); function Person (props ) { this .name=props.name||'匿名' ; this .garde=props.grade||1 ; } Person.prototype.hello=function ( ) { alert('Hello, ' +this .name+'!' ); } function createPerson (props ) { return new Person(props||{}); } var xiaogang=createPerson({name :'xiaogang' }); console .log(xiaogang.garde); </script > </body > </html >
原型继承
这个太复杂还用不到,不学了
class继承
这个语法很舒服啊,比上面的舒服多了,直接看这个。
唯一缺点是语法太新,有些浏览器不支持这种写法。但是可以用https://babeljs.io/这个工具转换成原始的代码。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 class Student { constructor (name ) { this .name=name; } hello ( ) { alert('Hello, ' +this .name+'!' ); } } class PrimaryStudent extends Student { constructor (name,grade ) { super (name); this .grade=grade; } myGrade ( ) { alert('I am at grade ' +this .grade); } }
语法和Java出奇地相似啊!