如何扩展此范围以便以下工作?我尝试过使用.bind()函数,但似乎无法使用任何东西。
var myObj = {
test: "Hello",
test2: " World",
run: {
all: function() {
return this.test + this.test2;
},
part: function() {
return this.test2;
}
}
}
console.log(myObj.run.all())
// => "Hello World"
console.log(myObj.run.part())
// => " World"
答案 0 :(得分:1)
函数all
和part
是对象run
的成员,run
没有值test
和test2
。它们是myObj
的成员对象。
您可以将this
关键字替换为myObj
。
var myObj = {
test: "Hello",
test2: " World",
run: {
all: function() {
return myObj.test + myObj.test2;
},
part: function() {
return myObj.test2;
}
}
}
console.log(myObj.run.all())
console.log(myObj.run.part())
答案 1 :(得分:0)
我最近遇到了同样的问题。 我通过使用函数
解决了var myObj = function(){
var self = this;
this.test = "Hello";
this.test2 = " World";
this.run = {
all: function() {
return self.test + self.test2;
},
part: function() {
return self.test2;
}
}
}
console.log(myObj.run.all())
// => "Hello World"
console.log(myObj.run.part())
// => " World"
我还发现 bind 可以完成工作!
var myObj = {
test: "Hello",
test2: " World",
run: {
all: function() {
return this.test + this.test2;
},
part: function() {
return this.test2;
}
}
};
console.log( myObj.run.all.bind(myObj)() );
// => "Hello World"
console.log( myObj.run.part.bind(myObj)() );
// => "World"
工作小提琴==> https://jsfiddle.net/sn5w7872/
答案 2 :(得分:0)
使用apply
#change the value in return to set the single color need, in hsl format.
def grey_color_func(word, font_size, position,orientation,random_state=None, **kwargs):
return("hsl(230,100%%, %d%%)" % np.random.randint(49,51))
#create the wordcloud object
wordcloud = WordCloud(background_color='white',max_font_size = 50).generate(tmp)
#change the color setting
wordcloud.recolor(color_func = grey_color_func)
方法调用具有给定apply()
值的函数,并将参数作为数组提供
this
答案 3 :(得分:-1)
使用ES6类和箭头函数。
class myObj {
constructor() {
this.test = "Hello";
this.test2 = " World";
this.run = {
all: () => this.test + this.test2,
part: () => this.test2
}
}
}
var obj = new myObj();
console.log(obj.run.all())
// => "Hello World"
console.log(obj.run.part())
// => " World"