Skip to content
This repository has been archived by the owner on Apr 22, 2023. It is now read-only.

vm instanceof operator don't work as expected #1277

Closed
davidarias opened this issue Jul 5, 2011 · 10 comments
Closed

vm instanceof operator don't work as expected #1277

davidarias opened this issue Jul 5, 2011 · 10 comments

Comments

@davidarias
Copy link

The following code returns false

vm.runInNewContext("a instanceof Array", {a:[]})
@ghost
Copy link

ghost commented Jul 5, 2011

Not a bug. New context and old context have each their own, distinct, Array object.

@isaacs
Copy link

isaacs commented Jul 5, 2011

Yes. Not sharing the global builtins is the point of running in a new context ;)

If you want to share specific globals, you can do it this way:

vm.runInContext("a instanceof Array", vm.createContext({a:[], Array:Array}))

EDIT I guess this way is easier, and closer to the original code:

vm.runInNewContext("a instanceof Array", {a:[], Array:Array})

@ghost
Copy link

ghost commented Jul 5, 2011

But if it is about (cross-context) Array testing, Array.isArray(a) is the way to go (unless I am mistaken, but I was told it works over context boundary as well).

@isaacs
Copy link

isaacs commented Jul 5, 2011

Yes, Array.isArray() is the best way to test if something is an array.

@davidarias
Copy link
Author

Thank you very much people, that clears my trouble :)

@bpaf
Copy link

bpaf commented Dec 6, 2011

Consider the following:

https://github.com/visionmedia/express/blob/master/examples/route-loading/boot.js

https://github.com/visionmedia/express/blob/master/lib/router/route.js#L71

app.get(/^\/foo\/…$/, …)

One work-around is passing RegExp:RegExp in the context and doing:

app.get(new RegExp('^\\/foo\\/…$'), …)

but is there a way to make it work with literals?

@bnoordhuis
Copy link
Member

@bpaf: Like this?

> require('vm').runInNewContext('re instanceof RegExp', {re:/x/})
false
> require('vm').runInNewContext('new RegExp(re) instanceof RegExp', {re:/x/})
true

@marcopaz
Copy link

actually there seems to be a bug here, node does not use the RegExp object passed in the context to create regexp objects from regexp literals.

@bnoordhuis
Copy link
Member

@brokendroid: To quote the Zen of Python, explicit is better than implicit.

@isaacs
Copy link

isaacs commented Dec 12, 2011

Works as designed.

> vm.runInNewContext("re instanceof RegExp", {re: /a/, RegExp: RegExp})
true

Same as the Array case.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

5 participants