__proto__
和prototype
有什么区别?
我看了很多文章,但是仍然不太理解。
据我所知,
__proto__
是原型对象的属性,
prototype
则是实际的对象。
我的理解对吗?
为什么只有函数有prototype
属性呢?
它怎么成为一个对象的呢?
var fn = function(){};
console.dir(fn);
输出
function fn()
arguments: null
caller: null
length: 0
name: ""
prototype: Object
__proto__: ()
<function scope>
使用对象和函数,我尝试在Chrome控制台中为__proto__
和原型设置值,如下所示。//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__
。 - nnnnnn