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

落爺英雄遲暮 提交于 2020-01-07 22:02:50
  • 原型继承 
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)
  }
}

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!