构造函数
构造函数与普通函数没有任何区别。只是在调用的时候通过 new 关键字来调用,用来生成一个对象
new 操作符
- 新建一个对象
- 把 this 指向给新建的对象
- this.xxx
- 把这个对象返回出去
实例:
function person() {this.name = '小绿';this.age = '18';this.hi = function() {alert('goodbye')}}var obj = new person();console.log(obj.name)console.log(obj.age)obj.hi();
原型对象
prototype 原型对象
函数对象才有的属性,proto 原型 指向构造函数的原型对象,所有的对象都有的属性
一个对象访问某个属性或者方法时,首先查找自身有没有这个属性或方法,如果有就直接访问,如果没有,就去查找原型 __proto__,对象的原型指向 该对象的构造函数的原型对象prototype ,如果构造函数的原型对象也没有这个属性或方法,去构造函数的原型__proto__查找,最终查找到 Object()的prototype,这个查找的过程叫原型链
实例:
function animal(duck, color, cool, name) {this.duck = duck;this.color = color;this.cool = cool;this.name = name;}animal.prototype.jiao = function() {console.log(this.duck);}animal.prototype.ys = function() {console.log(this.color);}animal.prototype.tz = function() {console.log(this.cool);}animal.prototype.mz = function() {console.log(this.name)}var animal1 = new animal('嘎嘎嘎', 'green', '酷', '小绿');var animal2 = new animal('汪汪汪', 'black and white', '傻屌', '二哈');console.log(animal1, animal2)animal1.jiao();animal1.ys();animal1.tz();animal1.mz();animal2.jiao();animal2.ys();animal2.tz();animal2.mz();console.log(animal2.toString())
注: 创建一个构造函数,通过prototype 传入一个新的方法:
当new 一个新的函数的时候,这个新的函数本身没有这个方法,的时候会通过proto找到原型对象中的这个方法并调用。
语法:
构造函数名.prototype.方法名 = function() {执行语句}animal.prototype.mz = function() {console.log(this.name)}
