Given these two objects:
var object1 = {
a: function() {},
b: function() {},
c: function() {}
};
var object2 = {
d: function() {},
e: function() {},
f: function() {}
};
Here we have two objects each containing 3 properties which are function objects (or, to be precise, references to function objects).
Let's say that f
is a reference to one of those 6 function objects. (It was declared like so: var f = object2.e;
or var f = objec开发者_C百科t1.c;
.)
How can I determine whether or not the reference f
is among the 3 references/properties of object1
?
The only thing you can do is to iterate over the object's properties:
var pointsToObject1 = false;
for(var prop in object1) {
// maybe call hasOwnProperty but I don't think it is necessary here.
if(f === object1[prop]) {
pointsToObject1 = true;
break;
}
}
f
is not really pointing to a property of one of the objects. It is more like both, f
and the property, point to the same value/object.
So this is my current solution (based on @Felix's answer):
function isIn(r, o) {
for (var p in o) {
if ( o.hasOwnProperty(p) ) {
if ( o[p] === r ) return true;
}
}
return false;
}
And then:
var f = object1.c;
and:
isIn(f, object1) // alerts "true"
isIn(f, object2) // alters "false"
Live demo: http://jsfiddle.net/W3Lub/
What do you think? I find it hard to believe that no browser or library offers this feature?!
精彩评论