document.createElement not working

前端 未结 5 1809
南方客
南方客 2021-01-16 06:20

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 objec

5条回答
  •  醉酒成梦
    2021-01-16 07:06

    That is happening because document.createElement uses this inside itself. When you call it like document.createElement() then this is set to document. But, when you save it as a variable, then this is no longer document, it's window.

    You need to call it with the context.

    var tag = document.createElement;  // you are saving the function, not its context
    var btn = tag.call(document, 'button'); // you need to set the context
    

    If your browser supports it, you can also use .bind:

    var tag = document.createElement.bind(document);
    var btn = tag('button');
    

提交回复
热议问题