Reputation: 9545
Please can you tell me why my .apply() is not working the way I want. What am I doing wrong?
I am expecting
Hi, Alice, I'm Bob
Hi, Steve, I'm Bob
Hi, Mark , I'm Bob
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
var friendlyGreet = function() {
$.each(arguments, function(index, val) {
alert("Hi, " + val.name + ", I'm " + this.name);
});
};
var Bob = {
name: "Bob"
};
var Alice = {
name: "Alice"
};
var Mark = {
name: "Mark"
};
var Steve = {
name: "Steve"
};
friendlyGreet.apply(Bob,[Alice,Steve,Mark]);
</script>
</head>
<body>
</body>
</html>
Upvotes: 1
Views: 445
Reputation: 8192
The apply
is working, but this
inside $.each
is referring to the element being looped on, and not the main object.
var friendlyGreet = function() {
var self = this;
$.each(arguments, function(index, val) {
alert("Hi, " + val.name + ", I'm " + self.name);
});
};
Upvotes: 4