[英]JavaScript Protoype confusion
I am new to JavaScript and experimenting with it these days. 我最近不熟悉JavaScript,现在正在尝试使用它。 I came to know that JavaScript is prototype based.
我知道JavaScript是基于原型的。 I tried executing below code:
我尝试执行以下代码:
var Person = function(name) {
this.name = name;
}
alert(Person.prototype);
var ram = new Person("Ram");
alert(ram.prototype);
As expected, the first alert prints [object, Object] , I expect the second alert prints the same, but it doesn't, why? 不出所料,第一个警报打印[object,Object] ,我希望第二个警报打印相同,但是为什么呢?
Can any please explain it clearly? 能请清楚解释吗?
Because the prototype
property on functions isn't the function's prototype, it's a property that will get used to set the prototype of objects created via the new
operator with that function. 因为函数上的
prototype
属性不是函数的原型,所以它是一个属性,用于设置通过new
运算符使用该函数创建的对象的原型。
You can access the object's prototype using ES5's Object.getPrototypeOf
: 您可以使用ES5的
Object.getPrototypeOf
来访问对象的原型:
var Person = function(name) {
this.name = name;
};
alert(Person.prototype);
var ram = new Person("Ram");
alert(Object.getPrototypeOf(ram));
On Firefox and several other browsers, you can use an upcoming ES6 feature (for JavaScript in browsers): The __proto__
accessor property: 在Firefox和其他几种浏览器上,您可以使用即将推出的ES6功能(用于浏览器中的JavaScript):
__proto__
访问器属性:
var Person = function(name) {
this.name = name;
};
alert(Person.prototype);
var ram = new Person("Ram");
alert(ram.__proto__); // ES6 feature, but already fairly common
Note that __proto__
is a property inherited from Object.prototype
, so if you create an object that doesn't inherit from Object.prototype
(eg, var o = Object.create(null);
or anything using that o
as a prototype), you can only use Object.getPrototypeOf
, not __proto__
. 需要注意的是
__proto__
是继承财产Object.prototype
,所以如果你创建一个对象,没有继承Object.prototype
(例如, var o = Object.create(null);
使用或任何o
为原型),您只能使用Object.getPrototypeOf
,而不能使用__proto__
。
The prototype
property of your object Person
is a property that you will only find in functions . 对象
Person
的prototype
属性是一个只能在函数中找到的属性。 To be clear, in JavaScript, functions are also objects with their own prototype . 需要明确的是,在JavaScript中, 函数也是具有自己原型的 对象 。 However, functions also have a special property named
prototype
which will become the prototype of every object made with that function as constructor. 但是, 函数还有一个特殊的属性,称为
prototype
,它将成为使用该函数作为构造函数的每个对象的原型 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.