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__
为什么工作?
最佳答案
__proto__
(这不是标准的(但可能很快)))设置一个对象的原型(prototype)。
.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
关于javascript - 为什么这种行为?__proto__ vs 原型(prototype)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16394709/