[英]Do I need to declare an object in javascript?
In java it is common to call methods without explicitly declaring objects for them. 在Java中,通常在没有显式声明对象的情况下调用方法。
eg: new Foo().bar("foobar");
例如: new Foo().bar("foobar");
I am new to javascript, it is fair enof to call it the same way ? 我是javascript的新手,以相同的方式称呼它是公平的吗?
new Foo().bar("foobar");
是new Foo().bar("foobar");
allowed in javascript 在javascript中允许 OR 要么
Do I need to declare a variable 我需要声明一个变量吗
var foo = new Foo(); foo.bar("foobar"); ?
Yes, you can call a method without declaring a variable. 是的,您可以在不声明变量的情况下调用方法。 Because initialization with the new operator will return a new instance of an object. 因为使用new运算符进行初始化将返回对象的新实例。
function Foo(){
this.bar = function() {
alert('hi');
}
}
new Foo().bar(); // alerts hi
You can also make the method daisy-chainable. 您还可以使方法以菊花链方式链接。
function Foo(){
this.bar = function() {
alert('hi');
return this;
}
}
new Foo().bar().bar(); // alerts hi twice
Your 1, new Foo().bar("foobar");
您的1, new Foo().bar("foobar");
is both correct in the sense that it compiles and works as you expect, and also correct in the sense that it doesn't violate typical style conventions in JavaScript. 从它可以按预期编译和工作的意义上讲,这是正确的;从它没有违反JavaScript中的典型样式约定的意义上说,这也是正确的。
You can follow the rule of thumb that anything you assign to a variable can replace that variable (until that variable is updated), so: 您可以遵循经验法则,即分配给变量的任何内容都可以替换该变量(直到该变量被更新),因此:
var foo = ANYTHINGHERE
foo.bar("foobar");
can be replaced by 可以替换为
(ANYTHINGHERE).bar("foobar");
var foo = new Foo().bar('foobar') //will Work (was mistaken here originally)
var foo = null
foo = (new Foo()).bar('foobar') //will work
or as you said this will work as well. 或您说过的方法也可以。
var foo = new Foo()
foo.bar('foobar')
If you want an object 'Foo', with a property called 'bar' that is a function, then that is what you will want to create. 如果您想要一个对象“ Foo”,它具有一个名为“ bar”的属性,该函数是一个函数,那么这就是您要创建的对象。
var Foo = {}; // Create the object
Foo.bar = function(){ alert('hi'); } // Create the object method
Foo.bar(); // Call the method
This method is chainable as well. 此方法也是可链接的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.