gpt4 book ai didi

javascript - 参数模式(新想法 vs. 绑定(bind) vs. self/that 模式)

转载 作者:行者123 更新时间:2023-11-28 07:22:06 24 4
gpt4 key购买 nike

为了在回调中访问父级的“this”,我们主要使用两种常见模式:

(第一)- 那个( self ,我,..)模式:

this.something = "hello";
var that = this;

var callback = function(){
console.log(that.something); // hello
};

callback();

(2nd) — 绑定(bind)模式:

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);

关于javascript - 参数模式(新想法 vs. 绑定(bind) vs. self/that 模式),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30189913/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com