Javascript 论证模式(新想法vs.束缚vs.自我/该模式)
为了在回调中访问parrent的“this”,我们主要使用两种常见模式: (1)那(自我,我,…)模式:Javascript 论证模式(新想法vs.束缚vs.自我/该模式),javascript,syntax,callback,semantics,readability,Javascript,Syntax,Callback,Semantics,Readability,为了在回调中访问parrent的“this”,我们主要使用两种常见模式: (1)那(自我,我,…)模式: this.something = "hello"; var that = this; var callback = function(){ console.log(that.something); // hello }; callback(); this.something = "hello"; var callback = function(){ console.
this.something = "hello";
var that = this;
var callback = function(){
console.log(that.something); // hello
};
callback();
this.something = "hello";
var callback = function(){
console.log(this.something); // hello
}.bind(this);
callback();
(第二)绑定模式:
this.something = "hello";
var that = this;
var callback = function(){
console.log(that.something); // hello
};
callback();
this.something = "hello";
var callback = function(){
console.log(this.something); // hello
}.bind(this);
callback();
。。但今天我发现,我们实际上也可以使用带有参数的模式,它更干净、更兼容、也更有效:
this.something = "hello";
var callback = function(self){
console.log(self.something); // hello
};
(callback)(this);
优点显而易见:-无需过度继承
-非常简单的语法和可读性
-兼容性(与ie6等浏览器的兼容性)
-一点函数方法(它只是一个参数)
您对此有何看法?您可以在不使用Python风格的
self
参数的情况下获得此模式的优势:
this.something = "hello";
var callback = function() {
console.log(this.something); // hello
};
callback.call(this);
基于观点的问题也不是如此<代码>回调。调用(此)似乎是做同样事情的一种更简洁的方式。一切都是一种意见。在过去的10年里,我还没有在IT领域看到通用的完美解决方案;)