构造函数、实例、原型、原型链

84 阅读2分钟

1.学习目的

共享属性和方法,节约内存资源,防止变量污染

2.构造函数和实例对象

function Person(){}
var person1 = new Person()
var person2 = new Person()

定义

当用new去调用一个函数时,如上代码所示,

new Person()就是构造函数person1,person2就是实例对象

作用

一个构造函数可以有多个实例对象(一对多),这样可以生成多个相同属性、不同值的对象,如:

构造函数缺陷:内存浪费

function Person(name,age){
  this.name = name;
  this.age = age;
  this.sex = '男'
  this.say = function(){
    console.log('say')
  }
}
var p1 = new Person('张三',18);//创建新内存 地址
var p2 = new Person('李四',20);//创建新内存,每次生成实例对象属性sex和方法say都重复生成,造成内存浪费
console.log(p1.say == p2.say)//false

构造函数执行过程:

new Person():创建新的内存空间 --》this指向该内存 --》 执行函数体代码 --》 默认返回this

每次生成实例对象属性sex方法say都重复生成,造成内存浪费

解决方法

(1)使用全局变量声明函数(造成全局变量污染)

let say = function(){
  console.log('say')
}
function Person(){
  this.say = say
}
let p1 = new Person()
let p2 = new Person()
console.log(p1.say == p2.say)//true

(2)使用对象,解决内存浪费和变量污染(该对象变成污染源):原型前身

let obj = {
  say:function(){}
}
function Person(){
  this.say = obj.say
}

3.原型

解决构造函数 浪费内存和变量污染的问题

function Person(name,age){
  this.name = name;
  this.age = age;
  }
}
Person.prototype.sex = '男'
Person.prototype.say = function(){
  console.log('say')
}
var p1 = new Person('张三',18);//创建新内存 地址
var p2 = new Person('李四',20);//创建新内存 地址
console.log(p1.say == p2.say)//true

4.构造函数、实例对象、原型的关系

console.log(person1.__proto__ === Person.prototype)//true
console.log(Person === Person.prototype.constructor)//true

5.原型链

console.log(Object.getPrototypeOf(Person) === Person.prototype)//true
console.log(Person.prototype.__proto__ === Object.prototype)//

__proto__不是web标准,很多浏览器不显示,在开发中不使用,只用于学习研究