structConstructor returns JS constructor function for a struct type.
(t *types.Struct)
| 564 | |
| 565 | // structConstructor returns JS constructor function for a struct type. |
| 566 | func (fc *funcContext) structConstructor(t *types.Struct) string { |
| 567 | if t.NumFields() == 0 { |
| 568 | return `function() { this.$val = this; }` |
| 569 | } |
| 570 | |
| 571 | constructor := &strings.Builder{} |
| 572 | |
| 573 | ctrArgs := make([]string, t.NumFields()) |
| 574 | for i := 0; i < t.NumFields(); i++ { |
| 575 | ctrArgs[i] = fieldName(t, i) + "_" |
| 576 | } |
| 577 | |
| 578 | fmt.Fprintf(constructor, "function(%s) {\n", strings.Join(ctrArgs, ", ")) |
| 579 | fmt.Fprintf(constructor, "\t\tthis.$val = this;\n") |
| 580 | |
| 581 | // If no arguments were passed, zero-initialize all fields. |
| 582 | fmt.Fprintf(constructor, "\t\tif (arguments.length === 0) {\n") |
| 583 | for i := 0; i < t.NumFields(); i++ { |
| 584 | zeroValue := fc.zeroValue(fc.fieldType(t, i)) |
| 585 | fmt.Fprintf(constructor, "\t\t\tthis.%s = %s;\n", fieldName(t, i), fc.translateExpr(zeroValue).String()) |
| 586 | } |
| 587 | fmt.Fprintf(constructor, "\t\t\treturn;\n") |
| 588 | fmt.Fprintf(constructor, "\t\t}\n") |
| 589 | |
| 590 | // Otherwise initialize fields with the provided values. |
| 591 | for i := 0; i < t.NumFields(); i++ { |
| 592 | fmt.Fprintf(constructor, "\t\tthis.%[1]s = %[1]s_;\n", fieldName(t, i)) |
| 593 | } |
| 594 | fmt.Fprintf(constructor, "\t}") |
| 595 | return constructor.String() |
| 596 | } |
| 597 | |
| 598 | // methodListEntry returns a JS code fragment that describes the given method |
| 599 | // function for runtime reflection. It returns isPtr=true if the method belongs |
no test coverage detected