Javascript中这两个函数声明有什么区别?
What's the difference between these two function declarations in Javascript?
我对这两个 javascript 案例有一些疑问:
function some() {
this.some2 = function() {//this is associated with own object(Correct?)
console.log('some2');
}
}
var __s1 = new some();
__s1.some2();//Allright, this do the work;
//some().some2();//This not work
这个声明类型有技术名称吗?也许是对象模式?
另一个类似的案例是:
function some() {
return {
some2: function() {
console.log('some2');
}
}
}
var __s2 = new some();
__s2.some2(); // Right, this work;
some().some2(); //Also work ... Ok, "some()" returns a object that contain
//the some2().
这第二种情况,也有技术名称?
他们之间最好的情况是什么?
第一个是使用原型。调用 new some()
创建一个新对象,在函数执行期间将 this
设置为该对象,并 returns 新对象。在这种情况下调用 some()
是没有意义的,因为在执行 some
时没有任何东西可以设置 this
(尽管该函数仍然会执行。)
第二种情况是returns一个对象的普通函数。它没有技术名称。
与第二种情况类似的是闭包。你可以,
function some() {
return function() {
console.log('some2');
}
然后
var s3= some();
s3() //prints some2
在您的第一个片段中,您将一个函数关联到名为 some2
的 属性。
在 JS 函数中首先是 class 对象,因此它们可以具有其他属性,当您调用 some2
时,您实际上是在 some
函数上使用对象委托。
在你的第二个代码片段中,你使用 return
来 return 一个新的完整对象,在每次调用时都有一个新函数 some2
。当您启动一个基于 (new some()
) 的新对象时,您实际上 return 具有新功能的新对象,而不是像第一个片段中那样引用单个对象。
我对这两个 javascript 案例有一些疑问:
function some() {
this.some2 = function() {//this is associated with own object(Correct?)
console.log('some2');
}
}
var __s1 = new some();
__s1.some2();//Allright, this do the work;
//some().some2();//This not work
这个声明类型有技术名称吗?也许是对象模式?
另一个类似的案例是:
function some() {
return {
some2: function() {
console.log('some2');
}
}
}
var __s2 = new some();
__s2.some2(); // Right, this work;
some().some2(); //Also work ... Ok, "some()" returns a object that contain
//the some2().
这第二种情况,也有技术名称?
他们之间最好的情况是什么?
第一个是使用原型。调用 new some()
创建一个新对象,在函数执行期间将 this
设置为该对象,并 returns 新对象。在这种情况下调用 some()
是没有意义的,因为在执行 some
时没有任何东西可以设置 this
(尽管该函数仍然会执行。)
第二种情况是returns一个对象的普通函数。它没有技术名称。
与第二种情况类似的是闭包。你可以,
function some() {
return function() {
console.log('some2');
}
然后
var s3= some();
s3() //prints some2
在您的第一个片段中,您将一个函数关联到名为 some2
的 属性。
在 JS 函数中首先是 class 对象,因此它们可以具有其他属性,当您调用 some2
时,您实际上是在 some
函数上使用对象委托。
在你的第二个代码片段中,你使用 return
来 return 一个新的完整对象,在每次调用时都有一个新函数 some2
。当您启动一个基于 (new some()
) 的新对象时,您实际上 return 具有新功能的新对象,而不是像第一个片段中那样引用单个对象。