【问题标题】:Why this behaviour?__proto__ vs prototype?为什么会出现这种行为?__proto__ vs 原型?
【发布时间】:2013-05-06 08:19:06
【问题描述】:
    function Obj1(name){
        this.__proto__={
            Name:name,
            getName:function(){
                alert(this.Name); 
            }


        };

    }

    function Obj2(name){
       this.prototype={
           Name:name,
           getName:function(){
           alert(this.Name); 
           };


       };

    }
    x=new Obj1("blue shark");
    z=new Obj2("red shark");
    x.getName();
    z.getName();// error:z.getName() is not a function

两者有什么区别?有人说prototype 仅用于构造函数,但在这种情况下它不起作用....而不是__proto__ 为什么起作用?

【问题讨论】:

标签: javascript prototype


【解决方案1】:

__proto__(不是标准的(但可能很快))设置一个对象的原型。

.prototype 使用new 设置通过调用作为构造函数设置的函数创建的对象的原型

另外值得一提的是Object.create

以下是示例:

带有.prototype的伪经典:

function Car(){
   this.x = 15;
}
Car.prototype.y = 10;

var g = new Car();
g.y; // this is 10;

使用__proto__(不要使用这个!):

var g = {x:15};
g.__proto__ = {y:10};
g.y; // this is 10;

这种方式是正确的,不使用带有new的构造函数:

var g = Object.create({y:10}); //creates x with prototype {y:10}
g.x = 15;
g.y; // this is 10

这里是an interesting tutorial on MDN covering these

【讨论】:

  • 这是语言创造者 Brandon Eich 在__proto__ 上的有趣评论,顺便说一下mail.mozilla.org/pipermail/es-discuss/2010-April/010917.html
  • 但是z = new Obj2(),它是使用new创建的
  • @RomanticElectron 仔细阅读答案和示例 :) .prototype 设置在 构造函数 上。在您的示例中,您将设置 Obj2.prototype 而不是 this
【解决方案2】:

只有函数有原型属性。 你需要在函数self上设置原型。

function Obj2(name){
    this.name = name;
}

Obj2.prototype={
    getName:function(){
       alert(this.Name); 
    }
};

【讨论】:

    【解决方案3】:

    __proto__ 不是标准属性。

    无论如何,new 创建的每个对象都会从 构造函数(一个函数)的 .prototype 成员中获得一个原型。注意原型成员没有名字,不能直接访问,需要Object.getPrototypeOf(x)

    如果你想创建一个具有给定原型的对象,代码是Object.create(proto),它或多或少等同于

    function makeObjectWithPrototype(x) {
        function makeit() { }
        makeit.prototype = x;
        return new makeit();
    }
    

    【讨论】:

    • 这是 Crockford 的旧 BEGET 函数 :) 使用现代 JS,您可以改用 Object.create(这还有其他好处)。此外,您可以使用标准 Object.getPrototypeOf 获取对象的原型
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-31
    • 2018-07-27
    • 2014-06-07
    • 1970-01-01
    • 1970-01-01
    • 2016-11-27
    相关资源
    最近更新 更多