请看代码
代码一
<script type="text/javascript">
var animal = function(){};
var dog = function(){};
animal.price = 2000;
dog.__proto__ = animal;
var tidy = new dog();
console.log(dog.price) //2000
console.log(tidy.price) // undefined
</script>
代码二
<script type="">
var animal = function(){};
var dog = function(){};
animal.price = 2000;
dog.prototype = animal;
var tidy = new dog();
console.log(dog.price) //undefined
console.log(tidy.price) // 2000
</script>
为什么结果是相反的?
JavaScript中基于原型链的继承是怎么样的?
__proto__
是实例(如 tidy)访问原型对象,同时它是非标准的,ES5 标准方法是Object.getPrototypeOf()
prototype
是构造函数(如 Dog) 访问原型对象可以这样验证
但是到这里并没有体现基于原型链的继承