简体   繁体   English

为什么构造函数不能访问他原型的属性,但可以访问父原型的属性(原型的原型)

[英]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. 确实有效,因为AFunction对象的一个​​实例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM