返回其自身实例的Object [英] An Object that returns an instance of itself
问题描述
背景:我的最新项目无法使用大型图书馆,这让我很难过。我希望从任何库中获得一些东西,例如缺少的函数 addClass
, hasClass
, removeClass
,兼容 addEventListener
等等所以我创建了一个小对象,我想在其他时间看到一些意见,但是我在设置它时遇到了一些麻烦。
Background: My latest project cannot use a large library, which saddens me. There are a few things that I would like to have from any library such as the missing functions addClass
, hasClass
, removeClass
, compatible addEventListener
, etc. So I created a little object which I'd like some opinions on some other time, but I'm having a little bit of trouble setting it up how I'd like.
为方便使用,我希望对象在创建时返回自己的新实例。
鉴于:
$ = function() {
this.name = "levi";
return this;
};
console.log($());
我们得到DOMWindow而不是 $
因为JavaScript中的这个
的古怪性质。 对我来说更奇怪的是 console.log(new $()。name)
正确返回levi。如果此
绑定到窗口,为什么该对象正确获取值?。我们可以添加新的 console.log(new $())
,它可以工作。但是,我不想每次都写新的。所以我试过了:
We get DOMWindow instead of $
because of the quirky nature of this
in JavaScript. What's more strange to me is that console.log(new $().name)
properly returns "levi". If this
is bound to window, why did the object properly get the value?. We could just add new console.log(new $())
and it works. However, I don't want to write new everytime. So I tried:
$ = function() {
var obj = function() {
this.name = "levi";
};
return new obj();
};
console.log($());
这给了我想要的东西,但似乎有点不必将对象包装在函数内部创造它。此外,返回的对象是 obj
而不是 $
。比较测试会失败。
Which gives me what I want, but it seems a bit unnecessary to wrap the object inside of a function which creates it. Further more, the returned object is obj
and not $
. Comparison tests would fail.
还有什么方法可以做到这一点?有更优雅的解决方案吗?我对重新思考整个过程没有任何疑虑。我认为自己非常擅长使用JavaScript,但创建新的JavaScript是我非常新的。
What are some other ways this can be done? Is there a more elegant solution? I have no qualms about rethinking my entire process. I consider myself pretty good at using JavaScript, but creating new JavaScript is something I am very new to.
有没有人看到以下解决方案有什么问题吗?
Does anyone see anything wrong with the following solution?
$a = function() {};
$ = function() {
if (!(this instanceof $)) {
return new $();
}
this.name = "levi";
return this;
};
//helper function
var log = function(message) {
document.write((message ? message : '') + "<br/>");
};
log("$().name == window.name: " + ($().name == window.name)); //false
log("$().name: " + $().name); //levi
log("window.name: " + window.name); //result
log();
log("$a instanceof $: " + ($a instanceof $)); //false
log("typeof $a: " + (typeof $a)); //function
log("typeof $: " + (typeof $)); //function
它似乎在我的所有测试中都有效。
It appears to be working in all my tests.
推荐答案
做你想做的最简单的方法是(我认为):
The most simple way to do what you want would be (I think):
$ = function(){
if (!(this instanceof $)){
return new $;
}
this.name = 'levi';
return this;
}
事实上只返回这个
不会创建$的实例,因为这个
的创建方式是作为常规执行 $
function:在这种情况下,这个
的值指向全局对象(在浏览器中: window
,实际调用执行 $()
与窗口相同。$()
)。这可以说是javascript生活的事实。 console.log(new $()。name)
显示正确值的事实是因为您将该函数作为构造函数调用,该构造函数返回该构造函数的实例(即 $
的新实例。但是 console.log($()。name)
也将打印'levi',因为它返回属性为 name $ c的全局对象$ c>,即
window.name
。尝试 $(); console.log(name)
,你会看到 name
现在是一个全局变量。因此,如果您不想每次都使用 new
关键字,请检查您的函数是作为常规函数调用,还是作为实例的构造函数调用( === instanceof $
)在构造函数中。使用上面的方法实例构造函数,无论是否使用 new
进行实例化,总是 $
The fact that just returning this
doesn't create an instance of $ is because of the way this
is created executing $
as a regular function: in that case the value of this
points to the global object (within a browser: window
, actually calling executing $()
is the same as window.$()
). It's a fact of javascript life so to speak. The fact that console.log(new $().name)
shows the right value is because you call the function as a constructor, which returns an instance of that constructor (i.e. an new instance of $
). But console.log($().name)
will also print 'levi', because it returns the global object with property name
, i.e. window.name
. try $(); console.log(name)
and you'll see name
is a global variable now. So if you don't want to use the new
keyword every time, check if your function is called as a regular function, or as a constructor for an instance (=== instanceof $
) within the constructor function. With the above method an instances constructor, no matter if it's instantiated with or without new
will allways be $
也许您应该将问题的标题改为:'一个返回自身实例的对象[构造函数] '
Maybe you should rephrase the title of your question to: 'An Object [constructor] that returns an instance of itself'
也许此博客文章可以减轻额外的光。
Maybe this blog entry can shed extra light.
这篇关于返回其自身实例的Object的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!