【发布时间】:2016-09-03 14:46:54
【问题描述】:
__proto__和prototype有什么区别
我阅读了网络上的大部分文章,但我仍然无法理解它..
据我所理解
__proto__ 是原型对象的属性
prototype 是实际对象
我对么? ....
为什么只有函数有原型属性? 它又是如何成为对象的呢?
var fn = function(){};
console.dir(fn);
输出
function fn() arguments: null caller: null length: 0 name: "" prototype: Object __proto__: () <function scope>
使用对象和函数我尝试为__proto__设置值
和原型在 chrome 控制台中如下所示
//create object and display it
var o = {name : 'ss'};
console.dir(o);
输出
Object name: "ss", __proto__: Object
//set the values
o.__proto__ = 'aaa';
o.prototype = 'bbb';
//after set the values display the object
console.dir(o);
输出
Object name: "ss", prototype: "aaa", __proto__: Object
//create function and display it
var fn = function(){};
console.dir(fn);
输出
function fn() arguments: null caller: null length: 0 name: "" prototype: Object __proto__: () <function scope>
//set the values
fn.prototype = 'fff';
fn.__proto__ = 'eee';
//after set the values display the object
console.dir(fn);
输出
function fn() arguments: null caller: null length: 0 name: "" prototype: "fff" __proto__: function() <function scope>
然后我意识到我无法为 __proto__ 设置值,但可以将值设置为 prototype 。为什么我不能为__proto__ 设置值???
【问题讨论】:
-
函数的
.prototype属性不会影响函数本身,它指的是将成为通过new调用该函数来实例化的对象的原型的对象。对象的.__proto__属性指的是该对象的实际原型。即Fn.prototype === (new Fn()).__proto__。
标签: javascript oop