JavaScript prototype实现静态方法(原型继承)

本文探讨了JavaScript中的原型继承,详细介绍了如何修改原型方法、如何在原型方法中调用实例方法以及实例方法如何调用原型方法。同时,还讨论了如何枚举原型方法和实例方法,为理解JS静态方法和原型链提供了深入理解。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  • 原型继承 
function Circle (radius) {
  // instance members
  this.radius = radius
}

// Prototype members
Circle.prototype.draw = function() {
  console.log('draw')
}

const c1 = new Circle(1)
const c2 = new Circle(2)

  • 修改原型方法
function Circle (radius) {
  // instance members
  this.radius = radius
}

// Prototype members
Circle.prototype.draw = function() {
  console.log('draw')
}
Circle.prototype.toString = function() {
  console.log(`radius is ${this.radius}`)
}
const c1 = new Circle(1)
const c2 = new Circle(2)

  •  原型方法调用实例方法
function Circle (radius) {
  // instance members
  this.radius = radius
  this.move = function() {
    console.log('move')
  }
}

// Prototype members
Circle.prototype.draw = function() {
  this.move()
  console.log('draw')
}
Circle.prototype.toString = function() {
  console.log(`radius is ${this.radius}`)
}
const c1 = new Circle(1)
const c2 = new Circle(2)

  • 实例方法调用原型方法 
function Circle (radius) {
  // instance members
  this.radius = radius
  this.move = function() {
    this.draw()
    console.log('move')
  }
}

// Prototype members
Circle.prototype.draw = function() {
  console.log('draw')
}
Circle.prototype.toString = function() {
  console.log(`radius is ${this.radius}`)
}
const c1 = new Circle(1)
const c2 = new Circle(2)

  • 枚举原型方法和实例方法
function Circle (radius) {
  // instance members
  this.radius = radius
  this.move = function() {
    console.log('move')
  }
}

// Prototype members
Circle.prototype.draw = function() {
  console.log('draw')
}
Circle.prototype.toString = function() {
  console.log(`radius is ${this.radius}`)
}
const c1 = new Circle(1)
// instance members
console.log(Object.keys(c1))
// All members
for (const key in c1) {
  console.log(key)
}
// Prototype members
for (const key in c1) {
  if (c1.hasOwnProperty(key)) {
    console.log(key)
  }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值