Skip to content

vm: instanceof test fails when assigning global to vm context #7351

Closed

Description

@princejwesley
  • Version: v6.1.0 , (master: v7.0.0-pre)
  • Platform: Darwin Princes-MacBook-Pro.local 15.5.0 Darwin Kernel Version 15.5.0: Tue Apr 19 18:36:36 PDT 2016; root:xnu-3248.50.21~8/RELEASE_X86_64 x86_64
  • Subsystem: vm

When assigning global variables to vm context, instanceof test for the assigned global variables return false

const vm = require('vm')

let ctx = vm.createContext();

let before = vm.runInContext('[] instanceof Array', ctx);
ctx.Array = Array;
let after = vm.runInContext('[] instanceof Array', ctx);

console.log('before =>', before, 'after =>', after); // before => true after => false

before = vm.runInContext('/vm/ instanceof RegExp', ctx);
ctx.RegExp = RegExp;
after = vm.runInContext('/vm/ instanceof RegExp', ctx);

console.log('before =>', before, 'after =>', after); // before => true after => false
Question

Is this a bug or an expected behaviour?

Activity

  1. added
    vmIssues and PRs related to the vm subsystem.
    v8 engineIssues and PRs related to the V8 dependency.
    on Jun 21, 2016
  2. cjihrig commented on Jun 21, 2016

    @cjihrig
    Contributor

    Seems like expected behavior to me. Array references a different thing in each context.

  3. targos commented on Jun 21, 2016

    @targos
    Member

    Yes, that is expected behavior. You can work around this problem for arrays with Array.isArray that works across contexts.

  4. rubenstolk commented on Jun 21, 2018

    @rubenstolk

    A helpful workaround is to use a custom isInstanceOf utility method, e.g.:

    const isInstanceOf = (o, type) => Object.prototype.toString.call(o) === `[object ${type}]`;
    
    isInstanceOf(new RegExp('hello world', 'g'), 'RegExp'); --> true
    isInstanceOf(/hello world/ 'RegExp'); --> true
    isInstanceOf([] 'Array'); --> true
    isInstanceOf(new Error('Error'), 'Error'); --> true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    v8 engineIssues and PRs related to the V8 dependency.vmIssues and PRs related to the vm subsystem.

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions