每一个实例对象又有一个proto属性,指向的构造函数的原型对象,构造函数的原型对象也是一个对象,也有proto属性,这样一层一层往上找就形成了原型链。
实现原型链涉及如下代码模式:
function SuperType() { //创建第一个构造函数this.property = true;}SuperType.prototype.getSuperValue = function() { //给原型对象内添加方法return this.property;};function SubType() { //创建第二个构造函数this.subproperty = false;}// 继承 SuperTypeSubType.prototype = new SuperType(); //将第一个构造函数的实例化赋值给第二个函数的原型对象// 如果利用对象的形式修改了原型对象,别忘了利用constructor 指回原来的构造函数SubType.prototype.constructor = SubType;SubType.prototype.getSubValue = function () {return this.subproperty; //给原型对象内添加方法};let instance = new SubType(); //实例化对象console.log(instance.getSuperValue()); // true
上面代码中,第二个构造函数的原型对象使用了第一个构造函数的实例对象,内部的constructor也被修改,不再指向第二个构造函数,需要手动改回来
1. 原型对象中this指向
构造函数中的this和原型对象的this,都指向我们new出来的实例对象
function Person(uname, age) {this.uname = uname;this.age = age;}var that;Person.prototype.sing = function() { //给Person构造函数的原型对象添加方法console.log('唱歌');that = this;}var ym = new Person('袁某', 18);// 1. 在构造函数中,里面this指向的是对象实例 ymconsole.log(that === ym);//true// 2.原型对象函数里面的this 指向的是 实例对象 ym
通过原型为数组扩展内置方法
Array.prototype.sum = function() {var sum = 0;for (var i = 0; i < this.length; i++) {sum += this[i];}return sum;};//此时数组对象中已经存在sum()方法了 可以始终 数组.sum()进行数据的求
通过原型链向Array()构造函数的原型对象内添加新的方法
