在JavaScript中设置值到`__proto__`和`prototype`的含义

8

__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
2个回答

2

这其实非常简单。

  1. {object}.__proto__ 是一个对 {constructor function}.prototype 对象的引用。
  2. JavaScript 中的操作符 new {constructor function} (params) 会执行三个重要步骤:
    1. 创建一个新对象,我们称之为 'obj'。
    2. 使用这个新生对象 (obj) 的 this 调用 {constructor function}
    3. 设置 obj.__proto__ = {constructor function}.prototype;

就是这样了。

obj.__proto__ 可以建立起单向链表,用于查找对象本身未定义的属性。由于它被设置成了 {constructor function}.prototype 对象,因此我们可以将该原型视为对象方法的 "架子",即与对象实例相关联的函数。

例如:

function Foo() {} 
Foo.prototype.bar = function() { return "foo.bar here"; }

var obj = new Foo(); // creating object with __proto__ set to Foo.prototype;

obj.bar(); // will return "foo.bar here"

2
在大多数语言中,都有类和对象。类继承自其他类。
在JavaScript中,
继承是基于原型的。这意味着没有类。相反,一个对象从另一个对象继承。
继承,__proto__
当一个对象rabbit从另一个对象animal继承时,在JavaScript中这意味着设置了一个特殊的属性rabbit.__proto__ = animal。

enter image description here

当访问兔子的属性时,如果解释器在兔子中找不到它,它会沿着 __proto__ 连接并搜索动物。
var animal = { eats: true }
var rabbit = { jumps: true }
rabbit.__proto__ = animal  // inherit
alert(rabbit.eats) // => true
原型属性

当调用构造函数时,new 运算符会将新创建的对象的 __proto__ 属性隐式设置为构造函数的 prototype 属性的值。

var animal = { eats: true }
 function Rabbit(name) {
  this.name = name
}
Rabbit.prototype = animal
var rabbit = new Rabbit('John')
alert( rabbit.eats ) // => true

完整参考资料。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接