Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 为什么有些功能(…;)!=构造函数中的某些函数调用(this,&x2026;)_Javascript_Oop_Constructor - Fatal编程技术网

Javascript 为什么有些功能(…;)!=构造函数中的某些函数调用(this,&x2026;)

Javascript 为什么有些功能(…;)!=构造函数中的某些函数调用(this,&x2026;),javascript,oop,constructor,Javascript,Oop,Constructor,我总是假设某个函数(…)与某个函数完全相同。调用(this…)。这似乎不适用于构造函数/对象构造上下文中的调用: 函数类(成员、父级){ 函数(值){ 成员。初始化调用(此值); 归还这个; }; Ctor.prototype=成员; Ctor.prototype.\uuuu proto\uuuu=parent.prototype; 回归系数; } var基=类({ __初始化:函数(值){ 这个值=值; } }, {}); var Child=Class({ __初始化:函数(值){ //基数

我总是假设
某个函数(…)
某个函数完全相同。调用(this…)
。这似乎不适用于构造函数/对象构造上下文中的调用:

函数类(成员、父级){
函数(值){
成员。初始化调用(此值);
归还这个;
};
Ctor.prototype=成员;
Ctor.prototype.\uuuu proto\uuuu=parent.prototype;
回归系数;
}
var基=类({
__初始化:函数(值){
这个值=值;
}
}, {});
var Child=Class({
__初始化:函数(值){
//基数(值*2);← 不会像预期的那样工作
Base.call(this,value*2);//工作正常
}
},碱基);
Child.\uuuu init\uuuu
中,有必要使用对
Base.call(this,value)
的显式调用。如果我不使用这个冗长的表达式,
this
将在被调用的基本构造函数中命名全局对象(
window
)。使用
“use strict”
时,将抛出一个错误,因为在严格模式下没有全局对象

有人能解释一下为什么在这个例子中我必须使用
Func.call(this,…)


(使用Node.js v0.6.12和Opera 12.50进行测试。)

使用
调用函数。调用
与仅使用
()
调用函数不同。使用
.call
可以为第一个参数中的调用显式设置
this
的值。正常调用时,
值将隐式为全局对象或
未定义
,具体取决于是否启用了严格模式

func.call({}, 1); //Call the function func with `this` set to the object and pass 1 as the first argument

func(1); //Call the function func with 1 as the first argument. The value of this inside the function depends on whether strict mode is on or off.


我总是假设某个函数(…)与 一些函数。调用(这个…)。这似乎不适用于电话 在构造函数/对象构造上下文中:

那不是真的,它们从来都不一样。您可能会将其与调用函数作为某个对象的属性相混淆
obj.method()
意味着
obj
是方法调用的
this
的值,它实际上与
obj.method.call(obj)
相同