类与继承,面向对象
类:
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 | <script> class Person{ constructor(){ //构造器 //this 必须在构造器里面使用 this .age = 20 //类的属性 this .sayHello = function (){ //类的方法 console.log( 'hello' ); } } } //构建对象 var person = new Person() //无参构造 console.log(person); //person {age: 20, sayHello: ƒ} console.log(person.age); //20 person.sayHello() //hello //调用有参构造 //类名首字母必须大写 class不能被重复定义 class Person1{ // constructor 调用 new 的过程,每一次new里面的内容都会重新声明 constructor (age = 18,name= 'jack' ){ //构造器 //this必须在构造器里面使用 this指向实例化的对象 this .age = age //类的属性 this .name = name this .sayHello = function (){ //类的方法 console.log( 'hello' ); } } run(){ //在函数里面可以访问对应的this console.log( this .name + '跑' ); } } //使用new 调用的对应构造器的时候 就是在实例化的过程 而产生的对象被称为实例化对象 var person = new Person1(18, 'jack' ) console.log(person); //Person1 {age: 18, name: 'jack', sayHello: ƒ} var person1 = new Person1(18, 'jack' ) console.log(person1); //Person1 {age: 18, name: 'jack', sayHello: ƒ} person1.run() //jack跑 console.log(person1.sayHello == person.sayHello); //flase console.log(person1.run == person.run); //true </script> |
继承:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | <script> class Father{ constructor(){ this .age = 18; } run(){ console.log( '跑' ); } } //extends 关键词声明以后 在对应的constructor里面想要使用this 必须先写super() class Son extends Father{ constructor(){ super () //指向父类Person的构造器constructor this .name = 'jack' } } var son = new Son() console.log(son); //获取不到run |
构建对象的方式
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 | <script> class Person{ constructor(age){ //构造器,其实就是一个构造函数 this .age =age ; } } //new 关键词来构建 var person = new Person(18) console.log(person); //Person {age: 18} //使用new关键词来构建 function Person1(age){ this .age =age; } //new 关键词来构建 var person = new Person1(20) console.log(person); //Person1 {age: 20} //当前这个 类型是否是object console.log(person instanceof Person1); //true //使用工厂模式来构建对象 function factory(age){ //声明一个对象 var obj = new Object() //给对象加属性 obj.age = age //返回这个对象 return obj; } var person1 = factory(23) console.log(person1); //{age: 23} //当前这个类的类型是否是Person类型 console.log(person instanceof Person); //false </script> |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!