Skip to content

Commit

Permalink
js: generate es5 methods for valueOf() and toString() (#12928)
Browse files Browse the repository at this point in the history
Co-authored-by: pancake <pancake@nopcode.org>
  • Loading branch information
trufae and radare committed Dec 22, 2021
1 parent 2693631 commit cb65f2f
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 10 deletions.
22 changes: 16 additions & 6 deletions vlib/v/gen/js/builtin_types.v
Expand Up @@ -308,12 +308,22 @@ fn (mut g JsGen) gen_builtin_prototype(c BuiltinPrototypeConfig) {
g.writeln('$c.extras,')
}

g.writeln('valueOf() { return $c.value_of },')
g.writeln('toString() { return $c.to_string },')
// g.writeln('eq(other) { return $c.eq },')
g.writeln('\$toJS() { return $c.to_jsval }, ')
if c.has_strfn {
g.writeln('str() { return new string(this.toString()) }')
if g.pref.output_es5 {
g.writeln('valueOf: (function() { return $c.value_of }).bind(this),')
g.writeln('toString: (function() { return $c.to_string }).bind(this),')
g.writeln('\$toJS: (function() { return $c.to_jsval }).bind(this), ')
if c.has_strfn {
g.writeln('str: (function() { return new string(this.toString())).bind(this) }')
}
// g.writeln('eq: (function(other) { return $c.eq }).bind(this),')
} else {
g.writeln('valueOf() { return $c.value_of },')
g.writeln('toString() { return $c.to_string },')
g.writeln('\$toJS() { return $c.to_jsval }, ')
if c.has_strfn {
g.writeln('str() { return new string(this.toString()) }')
}
// g.writeln('eq(other) { return $c.eq },')
}
g.dec_indent()
g.writeln('};\n')
Expand Down
19 changes: 15 additions & 4 deletions vlib/v/gen/js/js.v
Expand Up @@ -1914,7 +1914,11 @@ fn (mut g JsGen) gen_struct_decl(node ast.StructDecl) {
// gen toString method
fn_names := fns.map(it.name)
if 'toString' !in fn_names {
g.writeln('toString() {')
if g.pref.output_es5 {
g.writeln('toString: (function() {')
} else {
g.writeln('toString() {')
}
g.inc_indent()
g.write('return `$js_name {')
for i, field in node.fields {
Expand All @@ -1930,7 +1934,11 @@ fn (mut g JsGen) gen_struct_decl(node ast.StructDecl) {
}
g.writeln('}`')
g.dec_indent()
g.writeln('},')
if g.pref.output_es5 {
g.writeln('}).bind(this),')
} else {
g.writeln('},')
}
}
for field in node.fields {
typ := g.typ(field.typ)
Expand All @@ -1946,8 +1954,11 @@ fn (mut g JsGen) gen_struct_decl(node ast.StructDecl) {
g.writeln(',')
}
}
g.writeln('\$toJS() { return this; }')

if g.pref.output_es5 {
g.writeln('\$toJS: (function() { return this; }).bind(this)')
} else {
g.writeln('\$toJS() { return this; }')
}
g.writeln('};\n')
g.dec_indent()

Expand Down

0 comments on commit cb65f2f

Please sign in to comment.