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

Sus*_*ha7 6 javascript oop

__proto__和之间有什么区别prototype

我在网上阅读了大部分文章,我仍然无法理解..据我所知 __proto__ ,原型对象的属性 prototype是实际对象我是否正确?....

为什么只有函数具有原型属性?它是如何成为一个对象?

var fn = function(){};
console.dir(fn);
Run Code Online (Sandbox Code Playgroud)



产量

function fn()
  arguments: null
  caller: null
  length: 0
  name: ""
  prototype: Object
  __proto__: ()
  <function scope>
Run Code Online (Sandbox Code Playgroud)

使用对象和函数我尝试__proto__
在chrome控制台中设置值和原型,如下所示

//create object and display it
var o = {name : 'ss'};
console.dir(o);
Run Code Online (Sandbox Code Playgroud)



产量

Object
      name: "ss",
      __proto__: Object
Run Code Online (Sandbox Code Playgroud)

//set the values
o.__proto__ = 'aaa';
o.prototype = 'bbb';

//after set the values display the object
console.dir(o);
Run Code Online (Sandbox Code Playgroud)



产量

 Object
      name: "ss",
      prototype: "aaa",
      __proto__: Object
Run Code Online (Sandbox Code Playgroud)

//create function and display it
var fn = function(){};
console.dir(fn);
Run Code Online (Sandbox Code Playgroud)


产量

function fn()
  arguments: null
  caller: null
  length: 0
  name: ""
  prototype: Object
  __proto__: ()
  <function scope>
Run Code Online (Sandbox Code Playgroud)



//set the values
fn.prototype = 'fff';
fn.__proto__ = 'eee';

//after set the values display the object
console.dir(fn);
Run Code Online (Sandbox Code Playgroud)

产量

function fn()
  arguments: null
  caller: null
  length: 0
  name: ""
  prototype: "fff"
  __proto__: function()
  <function scope>
Run Code Online (Sandbox Code Playgroud)


然后我意识到我不能设置值 __proto__ 但可以设置值prototype.为什么我不能为__proto__ ??? 设置值 ?

c-s*_*ile 2

其实这很简单。

  1. {object}.__proto__是对对象的引用{constructor function}.prototype
  2. JavaScript 中的运算符new {constructor function} (params)主要做三件事:
    1. 创建新对象,将其命名为“obj”。
    2. 将其设置为该新生对象 (obj){constructor function}进行调用。this
    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"
Run Code Online (Sandbox Code Playgroud)