JS面向对象

75 阅读1分钟

创建对象的方式

  • 字面量
  • new Object()
  • 工厂模式
functuon createPerson(name,age) {
    var p = new Object()
    p.name = name
    p.age = age
    p.running = function() {}
    
    return p
}
var p = createPerson('zz',18)`

此方法创建的对象类型为Object类型

  • 构造函数
function Person(name,age) {
    this.name = name
    this.age = age
    this.running = function(){}
}
let p = new Person()

此方法会创建重复的函数

  • 构造函数和原型组合
function Person(name,age) {
    this.name = name
    this.age = age
}
Person.prototype.running = function() {}
var p = new Person('zz',18)
p.running()

new执行的操作

  1. 在内存中创建一个空的新对象
  2. 该对象内部的[[prototype]]属性(隐式原型)会被赋值为该构造函数的prototype属性(显式原型)
  3. 将构造函数内部的this指向创建出来的新对象
  4. 执行函数的内部代码
  5. 如果构造函数没有返回非空对象,则返回创建出来的新对象

判断对象是否为类的实例

class Person {
}
class Student extends Person() {
}
let p = new Person()
let s = new Student()
  • instanceof:判断构造函数的prototype是否出现在某个实例对象的原型链上
console.log(p instanceof Person) // true
console.log(s instanceof Student) // true
console.log(s instanceof Person) // true
console.log(p instanceof Object)  // true
  • constructor
console.log(p.constructor) // [class Person]
console.log(s.constructor)  // [class Student extends Person]