Javascript 模块模式没有给出正确的 instanceof

标签 javascript instanceof

有时候你认为你知道一些事情,然后事实证明你真的不知道......

在过去的几天里,我一直在对 Javascript 继承进行大量研究,以便在本地的技术小组进行演讲。没问题,我想,我知道这些东西,我会复习一下...

事实证明,我还有很多东西要学。这是让我感到惊讶的第一件事:

function Vehicle() {
   function move() {
      console.log('moving');
   }
   return {move: move}
}

function OtherVehicle() {
   this.alsoMove = function() {
      console.log('also moving')
   }
}

第一种方法是我一直理解的模块模式。第二个,虽然我不知道它的名字,但我知道它基本上是等价的 - 只是一个小的句法变化。

除了:

(new Vehicle()) instanceof Vehicle \\ returns false
(new OtherVehicle()) instanceof OtherVehicle \\ returns true

new Vehicle() 返回一个“对象”。
看着这个,这是有道理的,但这不是我所期待的。 任何人都可以解释这里发生了什么,为什么,也许可以给我指出一个非常好的资源来深入了解这个问题?

作为后续行动。

var Car = function() { 
   function drive() { console.log('driving') };
   return {drive: drive}
}

Car.prototype = new Vehicle() //I know, Object.create preferred

(new Car).move() //undefined

// However...
var Car = function() { 
   this.drive = function () { console.log('driving') };
}

Car.prototype = new Vehicle();
(new Car()).move() //output 'moving'

那么,模块模式不能用于继承吗?
还是我今天刚从床的另一边醒来,应该在下次触摸键盘之前去运行?

最佳答案

我不知道有什么特别好的resource ,但这里还是有一些反馈。

new Vehicle() returns an 'Object'.

return {} 覆盖默认返回值 this实例化对象。使用 new 调用此类函数毫无意义,因为 this 会被丢弃。就 OOP 语言而言,JavaScript 有点奇怪,因为它允许您在构造函数中为 this 返回另一个值。

所以是的,以这种方式使用的继承将不起作用:{} 本身不以任何方式链接到父类/基类,这就是为什么

(new Car).move() //undefined

未定义。

关于Javascript 模块模式没有给出正确的 instanceof,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33456582/

相关文章:

javascript - 如何使用 Javascript 获取 <label for> 值

javascript - 无法在 javascript 中用前一个元素兄弟递增最后一个元素

javascript - 如何在gmap上创建多个矩形?

Java 使用instanceof 但基于方法参数

java优化挑剔: is it faster to cast something and let it throw exception than calling instanceof to check before cast?

java - 类继承

java - 什么更快 : instanceof or isInstance?

javascript - Jint+JSfuck - 'Index was outside the bounds of the array'

javascript - setState 正在更新数组中所有元素的 css 属性

java - 在处理对象树时我应该避免 instanceof 吗?