[英]Why constructor function can't access property of his prototype, but can access property of parent prototype (prototype of prototype)
Following code, i checked using chrome browser console : 以下代码,我使用chrome浏览器控制台检查:
function A(){
this.a='a'
}
this is a constructor function.i have assined a property b
to the prototype of A
. 这是一个构造函数function.i已将属性
b
绑定到A
的原型。
A.prototype.b='b';
but when i access b
property using constructor function A
. 但是当我使用构造函数
A
访问b
属性时。 it is showing undefined
. 它显示
undefined
。
A.b //it return undefined
again i assigned property m
to the Function.prototype
, and the access using A
it return coorect vaue. 我再次将属性
m
分配给Function.prototype
,并使用A
进行访问返回coorect vaue。
Function.prototype.m='m';
A.m //it return "m"
So why constructor function can't access his prototype property,but can access parent prototype (protype of his prototype) property . 那么为什么构造函数不能访问他的原型属性,而是可以访问父原型(他的原型的protype)属性 。
You can't access A.prototype.b
because you haven't instantiated A
. 您无法访问
A.prototype.b
因为您尚未实例化A
Prototypes are objects which are created during the instantiation of an Object . 原型是在对象实例化期间创建的对象 。 In your example, here's how this might look:
在您的示例中,这可能是这样的:
// Create your constructor and prototype object
function A() {}
A.prototype = {
b: "b"
};
var a = new A();
console.log(a.b);
>>> "b"
However, in the case of Am
, A
(note, capital A, your constructor), is an instance of Function
, and so inherits all of it's attributes, including the one you've added. 但是,在
Am
的情况下, A
(注意,大写字母A,您的构造函数) 是 Function
一个实例,因此继承了它的所有属性,包括您添加的属性。
For more, I suggest you look at the MDN article on an introduction to Object-Oriented JavaScript 有关更多信息,我建议您查看有关面向对象JavaScript简介的MDN文章
You cannot access it as Ab
since A
is not an instance of A
constructor. 您不能将其作为
Ab
访问,因为A
不是A
构造函数的实例。 You need to: 你需要:
var instanceA = new A();
instanceA.b; // will work
Whereas 而
Function.prototype.m='m';
A.m //it return "m"
does work because A
is an instance of the Function
object. 确实有效,因为
A
是Function
对象的一个实例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.