regular JavaScript functions vs array functions

Does not have its own bindings to this or super, and should not be used as methods.

var obj1 = {
    a: 123,
    b: function() {
        return this.a;
    }
}

var obj2 = {
    a: 123,
    b: () => {
        return this.a;
    }
}

console.log("obj1: ", obj1.b());
console.log("obj2: ", obj2.b());

==========================================
result
==========================================

obj1:  123
obj2:  undefined

Using call/apply and bind

var obj1 = {
    a: 111,
    b: (a,b) => {
        return `${this.a} ${a} ${b}`;
    },
    c: function(a,b) {
        return `${this.a} ${a} ${b}`;        
    }
}

var obj2 = {
    a: 123
}

console.log("obj1: ", obj1.b.apply(obj2, ['one', 'two']));
console.log("obj1: ", obj1.b.bind(obj2)());


console.log("obj1: ", obj1.c.apply(obj2, ['one', 'two']));
console.log("obj1: ", obj1.c.bind(obj2, 'one', 'two')());

=====================================================
result
=====================================================
obj1:  undefined one two
obj1:  undefined undefined undefined
obj1:  123 one two
obj1:  123 one two

 

Leave a Reply