在_javascript中将值设置为__proto__`和`prototype

时间:2016-05-09 04:31:22

标签: javascript oop

__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__ ???

设置值

2 个答案:

答案 0 :(得分: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

原型

新函数调用将对象的__proto__设置为其prototype属性的值。

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

Complete Reference.

答案 1 :(得分:2)

实际上非常简单。

  1. {object}.__proto__是对{constructor function}.prototype对象的引用。
  2. JavaScript中的
  3. operator new {constructor function} (params)做了三件大事:
    1. 创建新对象,让它成为&#39; obj&#39;。
    2. 调用{constructor function} this设置为该新生对象(obj)。
    3. 设置obj.__proto__ = {constructor function}.prototype;
  4. 这就是它。

    obj.__proto__建立单个链表,用于查找未在对象本身中定义的属性。当它设置为{constructor function}.prototype对象时,我们可以将该原型视为&#34; rack&#34; for object methods - 与对象实例关联的函数。

    示例:

    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"
    
相关问题