JavaScript面向对象编程笔记

编程 · 2023-08-02 · 237 人浏览

构造函数和原型

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恒为当前实例,不会改变。
JavaScript
Theme Jasmine by Kent Liao