Javascript - 查找对象的容器

ale*_*rno 1 javascript

如果我创建一个对象

var O = { A : {}, B : {}}
Run Code Online (Sandbox Code Playgroud)

我接着说

O.A.foo = function() { }
O.B.foo = function() { }
Run Code Online (Sandbox Code Playgroud)

怎样才能foo()找出其父是否A还是B

Mat*_*all 6

this 关键是:

O.A.foo = O.B.foo = function() {
    if (this === O.A) {
        // it's A
    }
    else if (this === O.B) {
        // it's B
    }
}
Run Code Online (Sandbox Code Playgroud)

http://jsfiddle.net/mattball/2nhnH/


然而,这似乎有点代码味道.