繁体   English   中英

为什么不在子类中调用超级构造函数就不能访问超级类属性?

[英]Why can't we access Super Class Properties without calling Super Constructor in the Subclass?

  1. 为什么不在子类中调用超级构造函数就不能访问超级类属性?

     // Shape - superclass function Shape() { this.x = 10; this.y = 20; } // Rectangle - subclass function Rectangle() { // Shape.call(this); } // subclass extends superclass // inheritance part code Rectangle.prototype = Object.create(Shape.prototype); Rectangle.prototype.constructor = Rectangle; var rect = new Rectangle(); console.log( rect instanceof Shape); // true console.log(rect.x); // undefined console.log(rect.y); // undefined 
  2. 如果我在子类中调用Super Constructor,则可以在不编写继承代码部分的情况下使用Sub Class Object访问Super Class属性,那么这是否意味着我们仅需调用超类构造函数就无需编写用于实现继承的代码? 但是在这种情况下,我观​​察到子类对象rect不被视为Shape的instanceof因此我们没有实现继承,不是吗?

     // Shape - superclass function Shape() { this.x = 10; this.y = 20; } // Rectangle - subclass function Rectangle() { Shape.call(this); } // subclass extends superclass // inheritance part code // Rectangle.prototype = Object.create(Shape.prototype); // Rectangle.prototype.constructor = Rectangle; var rect = new Rectangle(); console.log( rect instanceof Shape); // false console.log(rect.x); // 10 console.log(rect.y); // 20 

建设者

您知道在那里所做的并不是一个真正的课程。 您创建了一个函数Shape ,另一个函数Rectangle 如果要两个函数都初始化您的对象,则必须确保它们都被调用了。 您甚至可以在同一对象上调用更多构造函数。

JavaScript中的构造函数的实际作用:当使用new运算符调用functionthis function this将是一个新的Object并且this.prototype将与该函数的prototype相同。 该对象还将在调用结束时返回。 因此,它与其他语言的构造器不同。

“遗产”

在完全不同的代码段中,您将Shape.prototype分配给Rectangle.prototype 这仅意味着,如果在Rectangle实例或Rectangle.prototype找不到属性,则Shape.prototype将在搜索的原型链中位于下一个位置。

原型的工作方式是:您需要一个名为myObject.x的值。 如果myObject没有这样的属性,则将返回myObject.prototype.x 如果不存在,将返回myObject.prototype.prototype.x 依此类推,直到到达Object.prototype 您还可以使用Object.prototype.hasOwnProperty区分实际上是对象的属性和继承的属性。

暂无
暂无

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

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