原型链,构造函数,继承 [英] Prototype chaining, Constructor, Inheritance

查看:88
本文介绍了原型链,构造函数,继承的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在玩javascript原型。我是新手,所以我有一个小问题。

I'm playing with javascript prototype. I'm new to it so I've got a small question.

我正在使用这个文章作为指南。

I'm using this article as a guide.

我已经定义了产品定义和书籍。 Book.prototype.constructor = Book(); 这个的目的是什么?我弄不清楚。我可以成功地调用父构造函数和不使用它。

I've got a Product defined and a Book defined. what is the purpose of Book.prototype.constructor = Book(); this. I can't figure out. I'm able to call parent constructor with and without it both successfully.

Book.prototype = new Product;
Book.prototype.constructor = Book; // What's the purpose of this

这是我的jsFiddle 链接

Here's my jsFiddle link

推荐答案

首先, new Product()使用Product函数的所有原型变量创建一个对象。因此,通过设置 Book.prototype = new Product(),Book继承了Product的所有原型变量。

First off, new Product() creates an object with all prototype variables of the Product function. So, by setting Book.prototype = new Product(), Book inherits all prototype variables of Product.

你可能会认为您也可以说: Book.prototype = Product.prototype ,但该解决方案无法按预期工作。 Book的原型成为Product的原型指针,因此它不是副本。如果你想改变Book的原型,它实际上在Product的原型中被改变了,那不是你想要的。

You might think you could also say: Book.prototype = Product.prototype, but that solution doesn't work as expected. The prototype of Book becomes a pointer to the prototype of Product, and therefore it's not a copy. If you would change something to the prototype of Book, it is actually changed in the prototype of Product, and that's not what you want.

很快, new Product()创建所有原型变量的副本。

Shortly, new Product() creates a copy of all prototype variables.

但是有一个这个方法也有问题。如果要立即创建新Book,则调用Product构造函数,而不是Book构造函数。要解决这个问题,你需要再次正确设置构造函数,它才能正常工作:

But there is a problem with this method too. If you would create a new Book now, the Product constructor is called, instead of the Book constructor. To solve that, you need to set the constructor correctly again, and it'll work:

Book.prototype.constructor = Book;
// Note: it's not Book(), but Book, it's a reference to the function

这篇关于原型链,构造函数,继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆