Javascript call() & apply() vs bind()?

后端 未结 22 1955
醉话见心
醉话见心 2020-11-22 02:42

I already know that apply and call are similar functions which setthis (context of a function).

The difference is with the way

22条回答
  •  失恋的感觉
    2020-11-22 03:39

    JavaScript Call()

    const person = {
        name: "Lokamn",
        dob: 12,
        print: function (value,value2) {
            console.log(this.dob+value+value2)
        }
    }
    const anotherPerson= {
         name: "Pappu",
         dob: 12,
    }
     person.print.call(anotherPerson,1,2)
    

    JavaScript apply()

        name: "Lokamn",
        dob: 12,
        print: function (value,value2) {
            console.log(this.dob+value+value2)
        }
    }
    const anotherPerson= {
         name: "Pappu",
         dob: 12,
    }
     person.print.apply(anotherPerson,[1,2])
    

    **call and apply function are difference call take separate argument but apply take array like:[1,2,3] **

    JavaScript bind()

        name: "Lokamn",
        dob: 12,
        anotherPerson: {
            name: "Pappu",
            dob: 12,
            print2: function () {
                console.log(this)
            }
        }
    }
    
    var bindFunction = person.anotherPerson.print2.bind(person)
     bindFunction()
    

提交回复
热议问题