在回答问题前,我们可以先了解他们是做什麽用的,为什麽总是拿来被比较?
这里要先回忆一个观念: JS里,所有的 函式 (function) 都是物件(object)。
Function objects inherit from Function.prototype. Function.prototype cannot be modified.
引用自Function.prototype | MDN
『 Function.prototype 这个属性,表示 Function
的原型物件,』
『 所有的Function物件都继承自Function.prototype ,且Function.prototype不能被修改。』
而 bind()
, call()
, apply()
是 Function.prototype 内建的方法(method),
被用来指定函式中this的指向。
那来依序看看它们的作用吧:
bind()
会建立一个新的函式(function),使这个函式中的this
被绑定至传入 bind()的 参数(parameter)。
Creates a new function which, when called, has its this set to the provided value, with a given sequence of arguments preceding any provided when the new function was called.
举例:
let mary = {
name: "Mary",
age: 22,
}
function getAge() {
console.log(this.age);
}
let getMarysAge = getAge.bind(mary);
getMarysAge(); // output: 22
观念 :
getAge
是一个function,也是一个object。getAge
里的this
keyword绑定给Mary
,并创造新的functiongetMarysAge
。call()
会直接呼叫(执行)一个函式,并将传入的值设为该函式的this。
Calls (executes) a function and sets its this to the provided value, arguments can be passed as they are.
举例:
let mary = {
name: "Mary",
age: 22,
}
function getAge() {
console.log(this.age);
}
getAge.call(mary); // output: 22
vs. bind
: call不会直接回传function,所以不需要给定variable就会直接执行。
那如果要执行call的函式,本身就需要传入参数的话,要怎麽办呢?
补充个有参数的例子:
let mary = {
name: "Mary",
age: 22,
}
function getAge(country, career) {
console.log("She is " + this.age + " years old");
console.log("She is a " + career + " from " + country);
}
getAge.call(mary, "Korean", "student");
// output: She is 22 years old ; She is a student from Korean
apply()
会直接呼叫(执行)一个函式,并将传入的值设为该函式的this。而传入参数的形式是array。
Calls a function and sets its this to the provided value, arguments can be passed as an Array object.
举例:
let mary = {
name: "Mary",
age: 22,
}
function getAge(country, career) {
console.log("She is " + this.age + " years old");
console.log("She is a " + career + " from " + country);
}
getAge.apply(mary, ["Korean", "student"]);
// output: She is 22 years old ; She is a student from Korean
vs. call
: parameter以阵列放入。
由此可知,我们可以知道:
【如内文有误还希望请不吝指教>< 谢谢阅览至此的各位:D 】
-----正文结束-----
prototype 翻译成原型,通常是研发完毕、在投入量产前完成的产品模型,
但它不是产品也不是模型。我上产品设计第一次听到这个词,问老师: 那是样品的意思吗? 他说不是。
(产品:拿来卖的。/模型:研发时模拟外观用的。/样品:给客人观赏用的。)
不知道有没有人跟我一样困惑过这个词,但我觉得在JS里面,prototype被解释的比较好懂。
讲那麽多,我只是在想明天可以写prototype。
GitHub:https://github.com/dannypc1628/Angular-Tou...
一般阅读的文章是由标题和段落文字组成,如果是长篇内容,容易让读者感到沉闷。这时候你可以试试适当加入...
本节是以 Golang 上游 8854368cb076ea9a2b71c8b3c8f675a8e1...
这篇会介绍 React 的一个新模式 Concurrent Mode 以及关於它的一些功能。 Con...
Q1. 什麽是 XSS? 跨网站指令码(Cross-Site Scripting,通常简称为XSS)...