Is there any difference between these two:
var test1 = function () {
this.method1 = function() {}
}
and
var test2 = function() {};
test2.method1 = function() {};
The first snippet takes this
object, whatever it is, and assigns a function to its slot (field) named method1
. this
can represent different objects, depending upon how test1
is called:
test1()
-- this
will be window
new test1()
-- this
refers to the object being createdcall
or apply
-- test1.apply(someObject)
-- this
refers to the argumentThe second snippet takes the object test2
and assigns a function to its slot named method1
.
The first way is a constructor that creates more objects and needs to have the new
keyword:
var mytest1 = new test1();
mytest1.method1();
The second way is ready to use right away:
test2.method1();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With