js面向对象:原型及继承

2018-10-09  本文已影响0人  WHU_GIS_LJ

1. __proto__prototypeObject.create()Object.getPrototypeOf()Object.setPrototypeOf()

1.1 __proto__
let a = {

    name: "luojian"

}

对象 a 的图示:

image.png
1.2 prototype
function A(id) {

    this.id = id

}

A.prototype.getID = function() {

    return this.id

}

构造函数 A 的图示:

image.png
1.3 Object.create()Object.getPrototypeOf()Object.setPrototypeOf()
let p = {

  name: "a"

}

let a = {}

let b = new Object()

let c = Object.create(null)

let d = Object.create(p)

console.log(a.__proto__) // Object

console.log(b.__proto__) // Object

console.log(c.__proto__) // undefined

console.log(d.__proto__) // p

console.log(Object.getPrototypeOf(d)) // p

// 将 d 的原型设置为 a

Object.setPrototypeOf(d, a)

console.log(Object.getPrototypeOf(d)) // a

2. javascript 继承

封装一个对象由构造函数与原型共同组成,因此继承也会分别有构造函数的继承原型的继承

先封装一个父类对象 Person

let Person = function(name, age) {

  this.name = name

  this.age = age

}

Person.prototype.getName = function() {

  return this.name

}

Person.prototype.getAge = function() {

  return this.age

}

Student 继承 Person

let Student = function(name, age, grade) {

  // 构造函数继承

  Person.call(this, name, age)

  this.grade = grade

}

Student.prototype = Object.create(Person.prototype, {

  // 重新指定新的constructor属性

  constructor: {

    value: Student

  },

  // 添加新的实例共享属性或方法

  getGrade: {

    value: function() {

      return this.grade

    }

  }

})
上一篇 下一篇

猜你喜欢

热点阅读