您当前的位置:首页 > 网站建设 > javascript
| php | asp | css | H5 | javascript | Mysql | Dreamweaver | Delphi | 网站维护 | 帝国cms | React | 考试系统 | ajax | jQuery | 小程序 |

深入了解javascript原型和原型链

51自学网 2022-02-21 13:35:35
  javascript

一、什么是原型

原型:每一个javascript对象(除null外)创建的时候,都会与之关联另一个对象,这个对象就是我们所说的原型,每一个对象都会从原型中“继承”属性。

例如

var obj = new Object();

创建一个对象的时候都会同时关联一个对象,如图,关联的这个对象就是新建的对象obj的原型

二、prototype

在JavaScript中,每个函数都有一个prototype属性,这个属性指向函数的原型对象。(ps:函数其实也是一个对象,所以与上述一、中的例子不冲突)

var obj = new Object();

所谓的prototype其实就是对象与对象的原型关联的属性,如图

例如:

 function Animal(weight) {   this.weight = weight }

如图表示对象与原型的关联:

每一个对象都会从原型中“继承”属性

例如:cat1和cagt2实例化了Animal,在cat1和cagt2本身是没有hieght属性的,但是能打印出height的值均为10,其实是在cat1和cagt2继承了原型Animal.prototype中的height属性

 function Animal(weight) {    this.weight = weight  }  Animal.prototype.height = 10  var cat1 = new Animal()  var cat2 = new Animal()  console.log('cat1',cat1.height)//10  console.log('cat2',cat2.height)//10

三、__proto__

这是每个对象(除null外)都会有的属性,叫做__proto__,这个属性会指向该对象的原型。

  function Animal(weight) {     this.weight = weight  }  Animal.prototype.height = 10  var cat1 = new Animal()  var cat2 = new Animal() console.log('cat1.__proto__ === Animal.prototype',cat1.__proto__ === Animal.prototype) console.log('cat2.__proto__ === Animal.prototype',cat2.__proto__ === Animal.prototype)

__proto__和prototype

  • __proto__是实例指向原型的属性
  • prototype是对象或者构造函数指向原型的属性

四、constructor

每个原型都有一个constructor属性,指向该关联的构造函数。

  function Animal(weight) {     this.weight = weight  }  Animal.prototype.height = 10  var cat1 = new Animal()  var cat2 = new Animal() console.log('cat1.__proto__ === Animal.prototype',cat1.__proto__ === Animal.prototype) console.log('Animal===Animal.prototype.constructor',Animal===Animal.prototype.constructor)// 获取原型对象 console.log('Object.getPrototypeOf(cat1) === Animal.prototype',Object.getPrototypeOf(cat1) === Animal.prototype)

更新关系图

cat1.__proto__
下载地址:
手机安装GreasyFork油猴js脚本的教程
proxy实现vue3数据双向绑定原理

万事OK自学网:51自学网_软件自学网_CAD自学网自学excel、自学PS、自学CAD、自学C语言、自学css3实例,是一个通过网络自主学习工作技能的自学平台,网友喜欢的软件自学网站。