2
    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__工作为什么?

4

3 回答 3

5

__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

这是一个关于 MDN 的有趣教程,涵盖了这些.

于 2013-05-06T08:20:28.350 回答
2

__proto__不是标准属性。

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

如果您想使用给定的原型创建一个对象,则代码Object.create(proto)或多或少等同于

function makeObjectWithPrototype(x) {
    function makeit() { }
    makeit.prototype = x;
    return new makeit();
}
于 2013-05-06T08:35:04.307 回答
2

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

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

Obj2.prototype={
    getName:function(){
       alert(this.Name); 
    }
};
于 2013-05-06T08:25:06.587 回答