Javascript 对嵌套函数中的父函数使用“this”
在Apple“classs”中,嵌套函数Javascript 对嵌套函数中的父函数使用“this”,javascript,jquery,class,oop,object,Javascript,Jquery,Class,Oop,Object,在Apple“classs”中,嵌套函数countSeeds()如何检索值this.price jsfiddle: 输出 17 undefined 将var self=this放在Apple的顶部,然后在嵌套函数中将其称为self i、 e: 您还可以将self=this语句放在this.cutOpen的开头,因为它仍然引用cutOpen中的Apple对象(因为它是Apple的一种方法) 更新 大多数evergreen浏览器现在都支持箭头函数,因此您可以像这样编写: Apple = funct
countSeeds()
如何检索值this.price
jsfiddle:
输出
17
undefined
将
var self=this
放在Apple的顶部,然后在嵌套函数中将其称为self
i、 e:
您还可以将self=this
语句放在this.cutOpen的开头,因为它仍然引用cutOpen中的Apple对象(因为它是Apple的一种方法)
更新
大多数evergreen浏览器现在都支持箭头函数,因此您可以像这样编写:
Apple = function() {
var self = this;
this.price = 17
this.cutOpen = function() {
console.log(this.price);
let countSeeds = () => {
console.log(this.price);
};
countSeeds();
}
}
这在IE11或其他较旧的浏览器中不起作用,除非您使用某种transpiler以较旧的javascript为目标。默认情况下,当您在不提供上下文的情况下调用函数时,
此
指的是窗口
对象。如果不喜欢默认设置,请尝试或设置上下文:
this.cutOpen = function() {
console.log(this.price);
countSeeds.call(this); //use call to set the context for the function.
function countSeeds() {
console.log(this.price);
}
}
我建议您将countSeeds
移动到构造函数之外,以防止它被多次重新定义:
function countSeeds() {
console.log(this.price);
}
Apple = function() {
this.price = 17
this.cutOpen = function() {
console.log(this.price);
countSeeds.call(this);
}
}
或者将countSeeds
定义为原型功能:
Apple = function() {
this.price = 17
this.cutOpen = function() {
console.log(this.price);
this.countSeeds(); //use countSeeds as an instance method.
}
}
Apple.prototype.countSeeds = function () {
console.log(this.price);
}
在我看来,
countSeeds
在这种情况下应该是一个实例方法,因为它总是访问当前实例的price
属性,如果这个是窗口
没有countSeeds()
更改本身的this
变量?函数上下文中的this对象设置为以下三个变量之一:1。如果函数是用new(newapple)调用的,那么它指的是构造函数将返回的对象。2.如果使用点语法(apple.cutOpen())或call或apply方法对对象调用函数,则该函数将引用该对象。3.如果直接调用该函数(countSeeds()),那么它将引用全局对象,在浏览器中它是窗口。您忘记了.call()
,.apply()
,.bind()
,括号语法相当于点符号和箭头函数(即将标准化)。需要记住的重要一点是,执行上下文的这个
绑定是通过调用函数的方式定义的。我要做的一个更改是,一旦您开始使用self
,就要使用它来避免代码中的任何混乱。因此,函数中的第二行是self.price=17当然,self.cutOpen=function(){
@FabrícioMatté我没有忘记.call()或.apply(),我在点语法之后就提到了它们。不过我没有提到bind,我也没有提到arrow语法,因为它还没有得到广泛的实现(尽管当它出现时,这将是这个问题的最佳答案).好电话。
function countSeeds() {
console.log(this.price);
}
Apple = function() {
this.price = 17
this.cutOpen = function() {
console.log(this.price);
countSeeds.call(this);
}
}
Apple = function() {
this.price = 17
this.cutOpen = function() {
console.log(this.price);
this.countSeeds(); //use countSeeds as an instance method.
}
}
Apple.prototype.countSeeds = function () {
console.log(this.price);
}