首页 代码 正文

JavaScript面向对象编程笔记

2023.8.2 代码 155

构造函数和原型

ES6之前没有提供 extends 继承,可以通过构造函数+原型对象模拟实现继承,被称为组合继承。

call()

调用这个函数并且修改函数运行时的 this 指向。

function fn() {
  console.log(this)
}
const obj = {
  name: "佩奇",
}
fn() //Window
fn.call(obj) //Object

继承父类属性:

function Father(name, age) {
  this.name = name
  this.age = age
}
function Son(name, age, score) {
  //把父构造函数的this改为子构造函数的this
  Father.call(this, name, age, score)
  this.score = score
}
const son = new Son("佩奇", 10, 99)
console.log(son) //Son {name: '佩奇', age: 10, score: 99}

继承父类方法:

function Father(name, age) {
  this.name = name
  this.age = age
}
Father.prototype.money = function () {
  console.log(10000)
}
function Son(name, age, score) {
  //把父构造函数的this改为子构造函数的this
  Father.call(this, name, age, score)
  this.score = score
}
Son.prototype = new Father()
Son.prototype.constructor = Son //利用constructor指回用来的构造函数
Son.prototype.exam = function () {
  console.log("儿子要考试!")
}
const son = new Son("佩奇", 10, 99)
console.log(Son.prototype.constructor) //Son

类中的所有代码都会在严格模式下执行。严格模式下其中一个特点就是,函数的this不在是window,而是undefined。

注意:

  • 在类中方法的this不是固定的:以方法形式调用时,this就是当前的实例;以函数形式调用,this是undefined
  • 在有些场景下,希望方法中的this是固定的,不会因调用方式不同而改变。可以使用箭头函数来定义类中的方法,则方法中的this恒为当前实例,不会改变。
  1. 转载请保留原文链接:JavaScript面向对象编程笔记 https://aboss.top/post/177/
  2. 本站所有资源文章出自互联网收集整理,本站不参与制作,如果侵犯了您的合法权益,请联系本站我们会及时删除。
  3. 本站发布资源来源于互联网,可能存在水印或者引流等信息,请用户擦亮眼睛自行鉴别,做一个有主见和判断力的用户。
  4. 本站资源仅供研究、学习交流之用,若使用商业用途,请购买正版授权,否则产生的一切后果将由下载用户自行承担。
  5. 联系方式(#替换成@):mail#aboss.top

评论

热门搜索