我以为我理解call
在javascript中是如何工作的,但显然不是。
function bear(){
var a = 1
pig.call(this)
}
function pig(){
alert(a) //throws an error, 'a is not defined'
}
bear()
http://codepen.io/anon/pen/jEYGOv
为什么这不起作用?我怎样才能使它工作(不将a
作为变量传递)
答案 0 :(得分:1)
你做不到。
function bear(){
pig.call(this);
}
function pig(){
this.a = 5; //same as window.a = 5 unless used as a constructor;
}
bear(); //window.a == 5;
a = new bear(); //this keyword is now referring to variable object a so a.a = 5;
.call(this)
的第一个参数之后的任何参数都是你在{/ 1}}上调用的函数的参数
答案 1 :(得分:1)
为什么这不起作用?我怎么能让它工作(没有通过as 变量)
您在此处所做的是与Function.prototype.call
分享上下文。共享上下文不共享范围变量。范围变量无法从范围外部访问,pig()
运行的范围与bear()
不同。
你能做的是
a。)在参数中发送公共变量:
// recommended
function bear(){
var a = 1;
pig(a);
}
function pig(a){
alert(a);
}
bear();
b。)将对象定义为公共上下文:
// not recommended
// hard to follow where the context is coming from
function bear(){
this.a = 1;
pig.call(this);
}
function pig(){
alert(this.a);
}
var o = {};
bear.call(o);
或
// recommended
var o = {
a: undefined,
bear: function (){
this.a = 1;
this.pig();
},
pig: function pig(){
alert(this.a);
}
};
o.bear();
c。)定义一个类
// not recommended
// you are defining the methods (bear and pig) by each instantiation
var My = function (){
this.bear = function (){
this.a = 1;
this.pig();
};
this.pig = function pig(){
alert(this.a);
};
};
var o = new My();
o.bear();
或
// recommended
var My = function (){};
My.prototype = {
constructor: My,
a: undefined,
bear: function (){
this.a = 1;
this.pig();
},
pig: function pig(){
alert(this.a);
}
};
var o = new My();
o.bear();
d。)在较高范围内定义公共变量
// not recommended
// (unless we are talking about a commonjs module which has its own scope)
// don't pollute the global scope with local variables
var a;
function bear(){
a = 1;
pig(a);
}
function pig(a){
alert(a);
}
bear();
或关闭
// recommended
(function (){
var a;
function bear(){
a = 1;
pig(a);
}
function pig(a){
alert(a);
}
bear();
})();
答案 2 :(得分:0)
您需要查看scope of variables:
<script type="text/javascript">
var a;
function bear(){
a = 1
pig.call(this)
}
function pig(){
alert(a);
}
bear();
</script>