js: generate es5 methods for valueOf() and toString() (#12928)

Co-authored-by: pancake <pancake@nopcode.org>
pull/12938/head
pancake 2021-12-22 08:20:45 +01:00 committed by GitHub
parent 2693631643
commit cb65f2ff44
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 31 additions and 10 deletions

View File

@ -308,13 +308,23 @@ fn (mut g JsGen) gen_builtin_prototype(c BuiltinPrototypeConfig) {
g.writeln('$c.extras,') g.writeln('$c.extras,')
} }
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('valueOf() { return $c.value_of },')
g.writeln('toString() { return $c.to_string },') g.writeln('toString() { return $c.to_string },')
// g.writeln('eq(other) { return $c.eq },')
g.writeln('\$toJS() { return $c.to_jsval }, ') g.writeln('\$toJS() { return $c.to_jsval }, ')
if c.has_strfn { if c.has_strfn {
g.writeln('str() { return new string(this.toString()) }') g.writeln('str() { return new string(this.toString()) }')
} }
// g.writeln('eq(other) { return $c.eq },')
}
g.dec_indent() g.dec_indent()
g.writeln('};\n') g.writeln('};\n')
g.writeln('function ${c.typ_name}__eq(self,other) { return $c.eq; } ') g.writeln('function ${c.typ_name}__eq(self,other) { return $c.eq; } ')

View File

@ -1914,7 +1914,11 @@ fn (mut g JsGen) gen_struct_decl(node ast.StructDecl) {
// gen toString method // gen toString method
fn_names := fns.map(it.name) fn_names := fns.map(it.name)
if 'toString' !in fn_names { if 'toString' !in fn_names {
if g.pref.output_es5 {
g.writeln('toString: (function() {')
} else {
g.writeln('toString() {') g.writeln('toString() {')
}
g.inc_indent() g.inc_indent()
g.write('return `$js_name {') g.write('return `$js_name {')
for i, field in node.fields { for i, field in node.fields {
@ -1930,8 +1934,12 @@ fn (mut g JsGen) gen_struct_decl(node ast.StructDecl) {
} }
g.writeln('}`') g.writeln('}`')
g.dec_indent() g.dec_indent()
if g.pref.output_es5 {
g.writeln('}).bind(this),')
} else {
g.writeln('},') g.writeln('},')
} }
}
for field in node.fields { for field in node.fields {
typ := g.typ(field.typ) typ := g.typ(field.typ)
g.doc.gen_typ(typ) g.doc.gen_typ(typ)
@ -1946,8 +1954,11 @@ fn (mut g JsGen) gen_struct_decl(node ast.StructDecl) {
g.writeln(',') g.writeln(',')
} }
} }
if g.pref.output_es5 {
g.writeln('\$toJS: (function() { return this; }).bind(this)')
} else {
g.writeln('\$toJS() { return this; }') g.writeln('\$toJS() { return this; }')
}
g.writeln('};\n') g.writeln('};\n')
g.dec_indent() g.dec_indent()