wrap instanceof to support @@hasInstance - fixes #1364

This commit is contained in:
Sebastian McKenzie 2015-04-28 14:27:30 +01:00
parent 0276c3ae81
commit 2952d94e60
11 changed files with 50 additions and 8 deletions

View File

@ -85,6 +85,7 @@ export default class File {
"temporal-assert-defined",
"self-global",
"default-props",
"instanceof",
// legacy
"interop-require",

View File

@ -0,0 +1,7 @@
(function (left, right) {
if (right != null && right[Symbol.hasInstance]) {
return right[Symbol.hasInstance](left);
} else {
return left instanceof right;
}
});

View File

@ -5,14 +5,16 @@ export var metadata = {
};
export function UnaryExpression(node, parent, scope, file) {
this.skip();
if (node._ignoreSpecSymbols) return;
if (node.operator === "typeof") {
var call = t.callExpression(file.addHelper("typeof"), [node.argument]);
if (this.get("argument").isIdentifier()) {
var undefLiteral = t.literal("undefined");
var unary = t.unaryExpression("typeof", node.argument);
unary._ignoreSpecSymbols = true;
return t.conditionalExpression(
t.binaryExpression("===", t.unaryExpression("typeof", node.argument), undefLiteral),
t.binaryExpression("===", unary, undefLiteral),
undefLiteral,
call
);
@ -22,6 +24,12 @@ export function UnaryExpression(node, parent, scope, file) {
}
}
export function BinaryExpression(node, parent, scope, file) {
if (node.operator === "instanceof") {
return t.callExpression(file.addHelper("instanceof"), [node.left, node.right]);
}
}
export function VariableDeclaration(node) {
if (node._generated) this.skip();
}

View File

@ -1,6 +0,0 @@
"use strict";
var _typeof = function (obj) { return obj && obj.constructor === Symbol ? "symbol" : typeof obj; };
var s = Symbol("s");
assert.equal(typeof s === "undefined" ? "undefined" : _typeof(s), "symbol");

View File

@ -0,0 +1 @@
a instanceof b;

View File

@ -0,0 +1,21 @@
var foo = { [Symbol.hasInstance]: function () { return true; } };
var bar = {};
assert.ok(bar instanceof foo);
assert.ok(new String instanceof String);
//
function Greeting(greeting) {
this.greeting = greeting;
}
Greeting[Symbol.hasInstance] = function(inst) {
return inst.greeting == "hello";
};
var a = new Greeting("hello");
var b = new Greeting("world");
assert.ok(a instanceof Greeting);
assert.ok(!(b instanceof Greeting));

View File

@ -0,0 +1,3 @@
"use strict";
babelHelpers._instanceof(a, b);

View File

@ -1,3 +1,4 @@
{
"externalHelpers": true,
"optional": ["es6.spec.symbols"]
}

View File

@ -1,2 +1,3 @@
var s = Symbol("s");
assert.equal(typeof s, "symbol");
assert.equal(typeof typeof s.foo, "symbol");

View File

@ -0,0 +1,5 @@
"use strict";
var s = Symbol("s");
assert.equal(typeof s === "undefined" ? "undefined" : babelHelpers._typeof(s), "symbol");
assert.equal(babelHelpers._typeof(babelHelpers._typeof(s.foo)), "symbol");