学习js数据结构与算法---笔记01--面向对象编程
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 82 83 84 85 | <script> function Book(name,page,auth){ this .name = name; this .page = page; this .auth = auth; } // 基于原型 Book.prototype.reading = function (user) { console.log(`${user}读${ this .name}`); } let book = new Book( '数据结构' ,100, '拖拉机' ) console.log(book.auth); book.reading( '小付' ); // 我们可以用 ES2015 把语法简化,如下所示 class BookTwo{ constructor(name,page,auth){ this .name = name; this .page = page; this .auth = auth; } reading(user){ console.log(`${user}读${ this .name}`); } } let book2 = new BookTwo( '数据结构' ,100, '拖拉机' ) console.log(book2.auth); book2.reading( '小付' ) /* 我们可以用 extends 关键字扩展一个类并继承它的行为(行{1})。在构造函数中,我们也 可以通过 super 关键字引用父类的构造函数(行{2})。 尽管在 JavaScript 中声明类的新方式所用的语法与 Java、C、C++等其他编程语言很类似,但 JavaScript 面向对象编程还是基于原型实现的。 */ // 继承 class ItBook extends Book{ constructor(name,page,auth,type){ super (name,page,auth) this .type = type; } payPrace(prace){ console.log(`${ this .name}花了¥${prace}购买${ this .type}类型的书`); } } let book3 = new ItBook( '数据结构' ,100, '拖拉机' , 'it' ) console.log(book3.type); book3.payPrace(100); // 使用属性存取器 /* ES2015 也可以为类属性创建存取器函数。虽然不像其他面向对象语言(封装概念),类的属 性不是私有的,但最好还是遵循一种命名模式。 下面的例子是一个声明了 get 和 set 函数的类。 */ class Person { constructor(name){ this ._name = name; // {1} } get name(){ return this ._name; // {2} } set name(value){ // {3} this ._name = value; } } let xiaoming = new Person( '小明' ) console.log(xiaoming._name,xiaoming.name); // {4} 小明 小明 xiaoming.name = '小红' ; // {5} console.log(xiaoming._name,xiaoming.name); // 小红 小红 xiaoming._name = '老王' ; // {6} console.log(xiaoming._name,xiaoming.name); // 老王 老王 /* 要声明 get 和 set 函数,只需要在我们要暴露和使用的函数名前面加上 get 或 set 关键字 (行{2}和行{3})。我们可以用相同的名字声明类属性,或者在属性名前面加下划线(行{1}), 让这个属性看起来像是私有的。 然后,只要像普通的属性一样,引用它们的名字(行{4}和行{5}),就可以执行 get 和 set 函数了。 _name 并非真正的私有属性,我们仍然可以引用它(行{6})。 */ </script> |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?