将方法添加到对象 [英] Adding methods to objects

查看:210
本文介绍了将方法添加到对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在JS编码一段时间后,我决定创建自己的框架。类似于jQuery的东西。但是一个非常非常简洁的版本。一些谷歌搜索后,我把这些代码放在一起:

  function $ elect(id){
if(window ===这个){
返回新的$ elect(id);
}
this.elm = document.getElementById(id);
}

$ elect.prototype = {
hide:function(){this.elm.style.display ='none'; },
show:function(){this.elm.style.display =''; },
toggle:function()
{
if(this.elm.style.display!=='none'){
this.elm.style.display ='没有';
} else {
this.elm.style.display ='';
}
}
};

到目前为止,这似乎奏效。但我对功能不感兴趣。我想了解这个逻辑。添加方法部分是可以理解的。虽然我不明白

 的功能if(window === this){
return new $ elect (ID);
}

如果我删除它,函数会中断。由于这是一个if语句,因此有2个结果。 True false 。所以我试图删除if语句,并使用 return new $ elect(id); 假设窗口===这个返回 true ,但那不起作用。然后我认为它可能会返回 false ,所以删除了整个if语句。这也没有奏效。有人能够启发我吗?此代码是否有效?我可能缺少一些东西。



刚刚在jsfiddle上测试过,它不起作用。虽然它适用于jsbin oO



jsfiddle jsbin



编辑:使用 $ elect(id).toggle(); 来调用它。虽然你可以检查演示。

解决方案


我想了解逻辑。


$ elect 是一个中的构造函数来解决这个问题。 //developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/newrel =nofollow noreferrer> new 关键字 ( new $ select )。如果不是( $ elect()),那么会发生什么?没有构建实例,并且 这个关键字将指向全局对象( window ) - 这是我们不想要的。所以这个片段是对这个场合的警惕,当它检测到它用 new 正确调用并返回它。



< blockquote>

如果我删除它,函数会中断

当你像 $ elect(id)没有警卫,它会为全局对象(本质上是一个全局变量)添加一个 elm 属性并返回任何内容。尝试调用 .toggle()方法会产生异常 undefined没有方法'toggle'


我试图删除if语句,假设窗口===这个返回true


那么你刚刚创建了一个无限递归函数,在调用时会导致堆栈溢出异常。






顺便说一句,正确的方法来防止 new -less调用不能与窗口(全局对象在非浏览器环境中可能有不同的名称),并假定其他一切正常,但要检查正确的继承。您只希望构造函数应用于类的实例,即从 $ elect.prototype 继承的对象。例如,当使用 new 进行调用时,可以保证这一点。要执行该检查,您将使用 instanceof 运算符

 函数$ elect(id){
if(!(this instanceof $ elect)){
return new $ elect(id);
}
this.elm = document.getElementById(id);
}

这也使得警卫的意图是明确的。


After coding in JS for a while I decided to make my own framework. Something similar to jQuery. But a very very stripped down version. After some googling I put together this code:

function $elect(id) {
    if (window === this) {
        return new $elect(id);
    }
    this.elm = document.getElementById(id);
}

$elect.prototype = {
    hide:   function () { this.elm.style.display = 'none';  },
    show:   function () { this.elm.style.display = '';      },
    toggle: function ()
            {
                if (this.elm.style.display !== 'none') {
                    this.elm.style.display = 'none';
                } else {
                    this.elm.style.display = '';
                }
            }
};

So far this seems to work. But I'm not interested in the functionality. I want to understand the logic. Adding methods part is understandable. Though I didn't understand the function of

    if (window === this) {
        return new $elect(id);
    }

If I remove it, function breaks. Since this is an if statement there are 2 results. True or false. So I tried to remove the if statement and just use return new $elect(id); assuming window === this returns true, but that didn't work. Then I thought it might return false, so removed the whole if statement. That also didn't work. Can someone enlighten me? Also is this code valid? I'm probably missing some stuff.

Just tested on jsfiddle and it doesn't work. Though it works on jsbin o.O

jsfiddle jsbin

EDIT: using $elect(id).toggle(); to call it. Though you can check the demos.

解决方案

I want to understand the logic.

$elect is a constructor function that is supposed to be called with the new keyword (new $select). If it is not ($elect()), what will happen then? There is no instance constructed, and the this keyword will point to the global object (window) - which we do not want. So this snippet is a guard against that occasion, when it detects that it invokes itself correctly with new and returns that.

If I remove it, function breaks

When you are calling it like $elect(id) without the guard, it will add a elm property to the global object (a global variable in essence) and return nothing. Trying to call the .toggle() method on that will yield the exception undefined has no method 'toggle'.

I tried to remove the if statement, assuming window === this returns true

Well, then you just created an infinite recursive function that will lead to a stack overflow exception when called.


Btw, the proper way to guard against new-less invocation is not to compare against window (the global object might have a different name in non-browser environments) and assume everything else to be OK, but to check for the correct inheritance. You want the constructor only to be applied on instances of your "class", i.e. objects that inherit from $elect.prototype. This is guaranteed when called with new for example. To do that check, you will use the instanceof operator:

function $elect(id) {
    if (! (this instanceof $elect)) {
        return new $elect(id);
    }
    this.elm = document.getElementById(id);
}

This also makes the intention of the guard explicit.

这篇关于将方法添加到对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆