When to Avoid Child.prototype = Parent.Prototype in JavaScript Inheritance
While it's common practice to inherit in JavaScript using Child.prototype = new Parent();, there are exceptions where Child.prototype = Parent.Prototype may cause unintended behaviors.
Consider the following snippet:
function GameObject(oImg, x, y) { this.x = x; this.y = y; this.img = oImg; this.hit = new Object(); this.hitBox.x = x; this.hitBox.y = y; this.hitBox.width = oImg.width; this.hitBox.height = oImg.height; } Spaceship.prototype = new GameObject(); Spaceship.prototype.constructor = Spaceship; function Spaceship(){ console.log("instantiate ship"); GameObject.apply(this, arguments); this.vx = 0; this.vy = 0; this.speed = 3; this.friction = 0.94; }
Upon inspecting the Spaceship constructor, you'll notice that its __proto__ property points to Spaceship, not GameObject. This is because the lines:
this.hitBox.width = oImg.width; this.hitBox.height = oImg.height;
assign properties directly to this.hitBox, which doesn't exist in the GameObject prototype. This behavior is problematic because it:
Why Use Child.prototype = new Parent(); Instead
Child.prototype = new Parent(); invokes the constructor of the Parent class and assigns its newly created instance to the Child prototype. This ensures that:
Alternative Solution
In modern browsers that support Object.create, you can use Spaceship.prototype = Object.create(GameObject.prototype); to create the child prototype. This is functionally equivalent to Child.prototype = new Parent(); but is more concise and avoids the unnecessary constructor call.
Atas ialah kandungan terperinci Bilakah Anda Harus Mengelak `Child.prototype = Parent.Prototype` dalam Pewarisan JavaScript?. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!