关于JavaScript-继承属性的应用,extends call prototype
extends用法演示
<script> class Father{ constructor(x, y){ this.x = x; this.y = y; } sum(){ console.log(this.x + this.y) } } class Son extends Father{ constructor(x, y){ super(x,y); // 调用了父类中的构造函数 } } var son = new Son(1,2); var son1 = new Son(11,22); son.sum(); son1.sum(); </script>
Father构造的方法,子类使用extends能够继承父类的方法, 子类使用super即可调用.
call的使用
<script> function fn(x, y){ console.log('我想喝手磨咖啡'); console.log(this); console.log(x + y); } var o = { name: 'andy' }; // call第一个函数用于改变指向 fn.call(o, 1, 2); function Star(role, age) { this.role = role; this.age = age; } var son = new Star('李白', 18) console.log(son.role); console.log(Star.role); </script>
输出结果 :
我想喝手磨咖啡
Objectname: "andy"[[Prototype]]: Object
3
李白
undefined
call第一个参数能够改变this的指向
<script> // 借用父构造函数继承属性 // 1.父构造函数 function Father(uname, age){ // this this.uname = uname; this.age = age; } Father.prototype.money = function(){ console.log(100000); } function Son(uname, age, score){ Father.call(this, uname, age); this.score = score; } // Son利用prototype指向Father 及Son拥有了父类的所有属性 Son.prototype = new Father(); // 对象的形式修改了原型对象,别忘了利用constructor 指回原来的构造函数 Son.prototype.constructor = Son; // 子构造函数专门的方法,由于Son在继承父类的属性后,给自己增加exam方法,所以父类是访问不到exam的 Son.prototype.exam = function() { console.log('孩子考试'); } var son = new Son('刘德华', 18, 100); console.log(son); console.log(Father.money); console.log(Son.prototype.constructor); console.log(son.exam()); console.log(Son.prototype.exam()); console.log(Father.prototype); console.log(Son.prototype); </script>
分类:
JavaScript
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 25岁的心里话
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现