且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

理解 JavaScript 中的原型继承

更新时间:2023-09-23 23:39:04

这两个块的不同之处在于在第一个示例中 Drive() 将只存在一次,而在第二种方法中 Drive() 将存在于每个实例中(每次你执行 new Car() 函数 drive() 将再次创建).或者说第一个使用原型来存储函数,第二个使用构造函数.函数的查找是构造函数,然后是原型.因此,对于您对 Drive() 的查找,无论它是在构造函数中还是在原型中,它都会找到它.使用原型更有效,因为通常每个类型只需要一个函数.

The two blocks differ in a way that in the first example Drive() will only exist once while at the second approach Drive() will exist per instance (Every time you do new Car() the function drive() will be created again). Or different said the first uses the prototype to store the function and the second the constructor. The lookup for functions is constructor and then prototype. So for your lookup of Drive() it finds it regardless if it is in the constructor or in the prototype. Using the prototype is more efficient because usually you need a function only once per type.

javascript 中的 new 调用会自动在原型中设置构造函数.如果要覆盖原型,则必须手动设置构造函数.

The new call in javascript automatically sets the constructor in the prototype. If you are overwriting the prototype so you have to set the constructor manually.

javascript 中的继承与 super 完全不同.所以如果你有一个子类,调用超级构造函数的唯一机会就是通过它的名字.

Inheritance in javascript has nothing like super. So if you have a subclass the only chance to call the super constructor is by its name.