0

This is the nth question about JS variable scope but I read through the rest and didn't quite get an answer.

var notification = window.webkitNotifications.createNotification(
'image.png',                      // The image.
'New Post: ',// The title.
'New stuff'// The body.
);

var itemLink = 'http://pathtothefile.com';

notification.onclick = function(itemLink) { 
window.focus(); 
window.open(itemLink,'_blank' );
this.cancel(); 
};

notification.show();

How do i get itemLink, which is defined in the global scope, to work in the onclick function?

1
  • 2
    Remove it from the parameter list. It's just in there automatically since it's a lower scope. Commented May 20, 2012 at 9:18

2 Answers 2

2

Remove the parameter from the function:

notification.onclick = function(itemLink) { // overrides itemLink in the global
                                            // object.

Fixed code:

notification.onclick = function() { 
    window.focus(); 
    window.open(itemLink,'_blank' );
    this.cancel(); 
};
Sign up to request clarification or add additional context in comments.

Comments

1

During name conflicts, local variables take precedence. Remove or rename the argument itemLink.

notification.onclick = function(something_else) { 
    //global itemLink should be accessible
};

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.