简体   繁体   English

javascript,原型无法制作自己的方法

[英]javascript, prototype can't make own method

I need to get this working, but I dont know why dosent working? 我需要使这个工作正常,但是我不知道为什么剂量工作? Any idea? 任何想法? Thanks for help! 感谢帮助!

(function( window ) {
    function select( selector ) {
        return document.querySelectorAll(selector);
    };

    select.prototype.attr = function(atitr)
    {
        return this.getAttribute(atitr);
    };

    window.j = select;
})( window );

console.log(j('.lol:last-child').attr('href'));

In the function you have: 在函数中,您具有:

function select( selector ) {
    return document.querySelectorAll(selector);
};

so select returns a NodeList, which doesn't inherit from select . 所以select返回一个NodeList,它不从select继承。 Then there is: 然后是:

window.j = select;

and

j(...).attr(...)

So select is called without new , so it doesn't create an instance of itself and assign it to this . 因此, 选择被称为没有新的 ,所以它不会创建自己的实例,并将其分配到这一点 Since that object isn't returned anyway, the returned object won't inherit from select even if you do call it with new . 由于无论如何都不会返回该对象,即使您使用new调用返回的对象也不会从select继承。

Edit 编辑

You can return an object that has the DOM elements as a property, eg: 您可以返回一个具有DOM元素作为属性的对象,例如:

<div class="lol">
  <a href="d" class="lol">sadas11DA</a>
  <a href="d31" class="lol">sadas222DA</a>
</div>

<script>

(function(window) {
  function Select(selector) {
    this.nodes = document.querySelectorAll(selector);
  }

  Select.prototype.attr = function(attribute) {
  console.log(this.nodes);
    return this.nodes[0]? this.nodes[0].getAttribute(attribute) : null;
  }

  window.j = Select;
}(this))

console.log(new j('.lol:last-child').attr('href'));

</script>

Note the modified markup. 注意修改后的标记。 Also passing of this rather than window since this can't be modified, window can. 由于不能修改, 因此也可以传递 窗口而不是窗口因此可以传递窗口

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM