javascript-为什么在构造函数中some_func(…)!= some_func.call(this,…)
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了javascript-为什么在构造函数中some_func(…)!= some_func.call(this,…),小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1587字,纯文字阅读大概需要3分钟。
内容图文
![javascript-为什么在构造函数中some_func(…)!= some_func.call(this,…)](/upload/InfoBanner/zyjiaocheng/675/05aea97795df4be68db58708cf17a33b.jpg)
我一直以为some_function(…)与some_function.call(this,…)完全相同.对于构造函数/对象构造上下文中的调用,似乎不成立:
function Class(members, parent) {
function Ctor(value) {
members.__init__.call(this, value);
return this;
};
Ctor.prototype = members;
Ctor.prototype.__proto__ = parent.prototype;
return Ctor;
}
var Base = Class({
__init__: function(value) {
this.value = value;
}
}, {});
var Child = Class({
__init__: function(value) {
// Base(value*2); ← WON'T WORK AS EXPECTED
Base.call(this, value*2); // works just fine
}
}, Base);
在Child .__ init__中,有必要使用对Base.call(this,value)的显式调用.如果我不使用这种冗长的表达方式,它将在被调用的基本构造函数中命名全局对象(浏览器中的窗口).使用“严格使用”时,由于在严格模式下没有全局对象,将引发错误.
有人可以解释为什么我必须在此示例中使用Func.call(this,…)吗?
(已通过Node.js v0.6.12和Opera 12.50进行了测试.)
解决方法:
用.call调用函数不同于仅用()调用函数.使用.call,您可以在第一个参数中显式设置此调用的值.在常规调用下,此值将隐式为全局对象或未定义,具体取决于是否启用了严格模式.
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.
查看.call
I always assumed that some_function(…) was exactly the same as
some_function.call(this, …). This seems not to hold true for calls
in constructors / an object construction context:
那是不对的,他们从不一样.您可能会将函数作为某个对象的属性来调用而使其混淆. obj.method()表示obj是该方法调用的值,它实际上与obj.method.call(obj)相同.
内容总结
以上是互联网集市为您收集整理的javascript-为什么在构造函数中some_func(…)!= some_func.call(this,…)全部内容,希望文章能够帮你解决javascript-为什么在构造函数中some_func(…)!= some_func.call(this,…)所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。