mirror of
https://github.com/robertkrimen/otto
synced 2025-10-12 20:27:30 +08:00
fix field accesses on anonymous embedded structs
This commit is contained in:
parent
37f8e9a246
commit
c382bd3c16
|
@ -36,8 +36,8 @@ func _newGoStructObject(value reflect.Value) *_goStructObject {
|
|||
}
|
||||
|
||||
func (self _goStructObject) getValue(name string) reflect.Value {
|
||||
if f, ok := self.field(name); ok {
|
||||
return reflect.Indirect(self.value).FieldByIndex(f.Index)
|
||||
if idx := fieldIndexByName(reflect.Indirect(self.value).Type(), name); len(idx) > 0 {
|
||||
return reflect.Indirect(self.value).FieldByIndex(idx)
|
||||
}
|
||||
|
||||
if validGoStructName(name) {
|
||||
|
@ -54,14 +54,8 @@ func (self _goStructObject) getValue(name string) reflect.Value {
|
|||
return reflect.Value{}
|
||||
}
|
||||
|
||||
func (self _goStructObject) field(name string) (reflect.StructField, bool) {
|
||||
t := reflect.Indirect(self.value).Type()
|
||||
|
||||
if idx := fieldIndexByName(t, name); len(idx) > 0 {
|
||||
return t.FieldByIndex(idx), true
|
||||
}
|
||||
|
||||
return reflect.StructField{}, false
|
||||
func (self _goStructObject) fieldIndex(name string) []int {
|
||||
return fieldIndexByName(reflect.Indirect(self.value).Type(), name)
|
||||
}
|
||||
|
||||
func (self _goStructObject) method(name string) (reflect.Method, bool) {
|
||||
|
@ -69,7 +63,7 @@ func (self _goStructObject) method(name string) (reflect.Method, bool) {
|
|||
}
|
||||
|
||||
func (self _goStructObject) setValue(rt *_runtime, name string, value Value) bool {
|
||||
if _, exists := self.field(name); !exists {
|
||||
if idx := fieldIndexByName(reflect.Indirect(self.value).Type(), name); len(idx) == 0 {
|
||||
return false
|
||||
}
|
||||
|
||||
|
|
33
type_go_struct_test.go
Normal file
33
type_go_struct_test.go
Normal file
|
@ -0,0 +1,33 @@
|
|||
package otto
|
||||
|
||||
import (
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestGoStructEmbeddedFields(t *testing.T) {
|
||||
type A struct {
|
||||
A1 string `json:"a1"`
|
||||
A2 string `json:"a2"`
|
||||
A3 string `json:"a3"`
|
||||
}
|
||||
|
||||
type B struct {
|
||||
A
|
||||
B1 string `json:"b1"`
|
||||
}
|
||||
|
||||
tt(t, func() {
|
||||
test, vm := test()
|
||||
|
||||
var b B
|
||||
|
||||
b.A1 = "a1"
|
||||
b.A2 = "a2"
|
||||
b.A3 = "a3"
|
||||
b.B1 = "b1"
|
||||
|
||||
vm.Set("v", B{A{"a1", "a2", "a3"}, "b1"})
|
||||
|
||||
test(`[v.a1,v.a2,v.a3,v.b1]`, "a1,a2,a3,b1")
|
||||
})
|
||||
}
|
Loading…
Reference in New Issue
Block a user