【转】javascript 的类,原型,继承的理解

原文: https://www.cnblogs.com/codernie/p/9098184.html

--------------------------------------------------------------------------------

1.类的prototype是什么?
   在Javascript中,每当我们定义一个构造函数,Javascript引擎就会自动为这个类中添加一个prototype(也被称作原型)
  2.对象的 proto 是什么?
   在Javascript中,每当我们使用new创建一个对象时,Javascript引擎就会自动为这个对象中添加一个__proto__属性,并让其指向其类的prototype

// 代码3.2
function Human(name) { this.name = name } console.log(Human.prototype) var person_test1 = new Human('Test1') var person_test2 = new Human('Test2') console.log(person_test1.__proto__) console.log(person_test2.__proto__) console.log(Human.prototype === person_test1.__proto__) // true console.log(Human.prototype === person_test2.__proto__) // true

我们会发现Human.prototype是一个对象,Human类的实例化对象person_test1、person_test2下都有一个属性__proto__也是对象,并且它们都等于Human.prototype,我们知道在Javascript中引用类型的相等意味着他们所指向的是同一个对象。所以我们可以得到结论,任何一个实例化对象的__proto__属性都指向其类的prototype

猜你喜欢

转载自www.cnblogs.com/oxspirt/p/9099698.html
今日推荐