如果我创建一个对象
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?
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/
然而,这似乎有点代码味道.