Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
89
rated 0 times [  93] [ 4]  / answers: 1 / hits: 22534  / 12 Years ago, mon, january 7, 2013, 12:00:00

I am creating a plugin using jQuery library.



Here i am storing String.prototype in a variable then i am using this variable to extend my Sting object. And this is working fine.



// String Prototyping store in a variable
// Save bytes in the minified version of js
var StrProto = String.prototype;
String.prototype.toProperCase = function () {
return this.replace(/wS*/g, function (txt) {
return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
});
};
// working fine
alert(yogesh kumar.toProperCase());


In the next case i am creating m function xyz which stored in
abc variable and this is also working fine.



function xyz(x){
alert(x)
}
var abc = xyz;
// working fine
abc(yogesh kumar);


In the last case i am storing document.createElement in a variable
tag and using tag to create a button. but this is not working.



var tag=document.createElement;
$(document.createElement(button)).html(document.Element).appendTo(#myDiv);

// not working
$(tag(button)).html(tag).appendTo(#myDiv);


Please check the link on jsFiddle:




click here




Error:



In Chrome




  • Uncaught TypeError: Illegal invocation



in Firefox




  • Error: NS_ERROR_XPC_BAD_CONVERT_JS: Could not convert JavaScript
    argument



Why this error?



What is the solution?


More From » jquery

 Answers
13

You are getting a reference to a function that is a member of the document. When you call that reference directly, it's context is now the window rather than the document. Here's an example:



http://jsfiddle.net/DeCNx/



var foo = {
createElement: function(tagname) {
if (this._secretvarthatisneeded) {
console.log(tagname + Element Created!);
}
},
_secretvarthatisneeded: true
}

foo.createElement(FOOBAR); // works

var bar = foo.createElement;
bar(BARFOO); // doesn't work
bar.call(foo,BARBAR) // works


Since the context was lost, the bar() call didn't result in a console.log();



obviously this is just a simplification to demonstrate.



Update: For the use you are making, i'd suggest doing this:



$.createElement = function(tagName,attributes){
return $(
document.createElement(tagName),
attributes ? attributes : {}
)
}


Now you can simply do $.createElement(button).html(tag).appendTo(#myDiv); It is fast and still easy to read. Note however IE has problems with inputs, if you're creating input elements, i suggest using $(<input type='text' />) rather than this.


[#81028] Sunday, January 6, 2013, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
harleew

Total Points: 70
Total Questions: 87
Total Answers: 117

Location: Namibia
Member since Mon, Feb 21, 2022
2 Years ago
;