Skip to content

Instantly share code, notes, and snippets.

@hvitorino
Created September 4, 2017 19:58
Show Gist options
  • Save hvitorino/33bc1d8b669136498ed5dc786ec136fc to your computer and use it in GitHub Desktop.
Save hvitorino/33bc1d8b669136498ed5dc786ec136fc to your computer and use it in GitHub Desktop.
this.name = "Heisenberg";
let obj = {
name: "i'm obj",
sayMyName: function() {
console.log(this.name);
},
sayMyArrowName: () => console.log(this.name)
};
obj.sayMyName();
obj.sayMyArrowName();
let anotherObj = {
name: "i'm another obj"
}
obj.sayMyName.bind(anotherObj)();
obj.sayMyArrowName.bind(anotherObj)();
@AlbertoMonteiro
Copy link

this.name = "Heisenberg";

let obj = {
    name: "i'm obj",
    sayMyName: function () {
        console.log(this.name, "sayMyName");
    },
    sayMyArrowName: () => console.log(this.name, "sayMyArrowName")
};

obj.sayMyName();
obj.sayMyArrowName();

let anotherObj = {
    name: "i'm another obj"
}

obj.sayMyName.bind(anotherObj)();
obj.sayMyArrowName.bind(anotherObj)();

function callTheFunction(func) {
    this.name = "I'm callTheFunction";
    func();
}

callTheFunction(obj.sayMyName);
callTheFunction(obj.sayMyArrowName);

let callTheFunctionSon = function (func) {
    func.bind({ name: "Son" })();
};

callTheFunctionSon = callTheFunctionSon.bind({ name: "I'm callTheFunctionSon" });

callTheFunctionSon(obj.sayMyName);
callTheFunctionSon(obj.sayMyArrowName);

Depois de fazer esses testes, percebi que o contexto de uma arrow function é imutável, portanto o bind não vai fazer efeito nenhum sobre isso.

Além disso, a arrow function veio para resolver o problema do contexto, e para tal, concordo com o comportamento que faz com que o bind não tenha nenhum efeito sobre seu contexto.

@hvitorino
Copy link
Author

Achei um ótimo recurso do ES6, apesar dessa inconsistência. JavaScript tá ficando fofo. Ainda não sei muito sobre ES7 mas chego lá.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment