1657024200
在本文中,我将通过简单的示例来解释如何在 JavaScript 中使用 call、apply 和 bind。
我们还将实现一个示例,展示如何使用 apply 函数创建自己的地图函数。
事不宜迟,让我们开始吧
让我们更仔细地看一下我们将在这里研究的函数,以了解它们的作用。
Call是一个函数,可以帮助您更改调用函数的上下文。用外行的话来说,它可以帮助您将this
函数内部的值替换为您想要的任何值。
Apply的功能非常相似call
。唯一的区别是apply
您可以将数组作为参数列表传递。
Bind是一个函数,可帮助您创建另一个函数,稍后您可以使用提供的新上下文执行该函数this
。
现在我们将看一些调用、应用和绑定函数的基本示例。然后我们将看一个示例,我们将构建自己的函数,类似于 map 函数。
call
是一个函数,用于更改this
函数内部的值并使用提供的参数执行它。
这是call
函数的语法:
func.call(thisObj, args1, args2, ...)
在哪里,
this
对象调用的函数this
函数内部的关键字替换func
this
对象的调用函数的参数。请注意,如果您调用一个没有任何thisObj
参数的函数,那么 JavaScript 会将此属性视为一个全局对象。
现在我们已经了解了call
函数是什么的一些背景信息,让我们从通过一些示例更详细地了解它开始。
考虑下面的例子。它由 3 个类组成 - Car
、Brand1
和Brand2
。
function Car(type, fuelType){
this.type = type;
this.fuelType = fuelType;
}
function setBrand(brand){
Car.call(this, "convertible", "petrol");
this.brand = brand;
console.log(`Car details = `, this);
}
function definePrice(price){
Car.call(this, "convertible", "diesel");
this.price = price;
console.log(`Car details = `, this);
}
const newBrand = new setBrand('Brand1');
const newCarPrice = new definePrice(100000);
如果你仔细看,你会发现我们使用call
函数调用了Car
两次函数。首先,在函数中setBrand
,然后在definePrice
函数中。
在这两个函数中,我们使用表示各自函数本身的对象来调用Car
函数。this
例如,在内部setBrand
,我们使用属于其上下文Car
的对象调用函数。this
情况与definePrice
.
考虑下面的例子:
const newEntity = (obj) => console.log(obj);
function mountEntity(){
this.entity = newEntity;
console.log(`Entity ${this.entity} is mounted on ${this}`);
}
mountEntity.call();
在这个例子中,我们调用了mountEntity
没有thisObj
参数的函数。在这种情况下,JavaScript 指的是全局对象。
该Apply
函数与函数非常相似Call
。call
和之间的唯一区别apply
是参数传递方式的不同。
在apply
, arguments 中,您可以将参数作为数组文字或新数组对象传递。
这是apply
函数的语法:
func.apply(thisObj, argumentsArray);
在哪里,
this
对象调用的函数this
函数内部的关键字替换func
正如您在上面看到的,该apply
函数具有不同类型的语法。
第一种语法很简单。您可以传入一个参数数组,如下所示:
func.apply(thisObj, [args1, args2, ...]);
第二种语法是我们可以将新数组对象传递给它的地方:
func.apply(thisObj, new Array(args1, args2));
第三种语法是我们可以传入 arguments 关键字的地方:
func.apply(thisObj, arguments);
arguments是函数内部可用的特殊对象。它包含传递给函数的参数值。您可以将此关键字与apply
函数一起使用以获取任意数量的任意参数。
最好的部分apply
是我们不需要关心传递给调用函数的参数数量。由于其动态性和多功能性,您可以在复杂的情况下使用它。
让我们看一下与上面相同的示例,但这次我们将使用该apply
函数。
function Car(type, fuelType){
this.type = type;
this.fuelType = fuelType;
}
function setBrand(brand){
Car.apply(this, ["convertible", "petrol"]); //Syntax with array literal
this.brand = brand;
console.log(`Car details = `, this);
}
function definePrice(price){
Car.apply(this, new Array("convertible", "diesel")); //Syntax with array object construction
this.price = price;
console.log(`Car details = `, this);
}
const newBrand = new setBrand('Brand1');
const newCarPrice = new definePrice(100000);
这是一个示例,展示了如何使用arguments
关键字:
function addUp(){
//Using arguments to capture the arbitrary number of inputs
const args = Array.from(arguments);
this.x = args.reduce((prev, curr) => prev + curr, 0);
console.log("this.x = ", this.x);
}
function driverFunc(){
const obj = {
inps: [1,2,3,4,5,6]
}
addUp.apply(obj, obj.inps);
}
driverFunc();
该函数在调用函数内部bind
创建一个具有新值的函数副本。this
这是bind
函数的语法:
func.bind(thisObj, arg1, arg2, ..., argN);
在哪里,
this
对象调用的函数this
函数内部的关键字替换func
call
函数。然后该bind
函数返回一个新函数,该函数包含一个新上下文到this
调用函数内部的变量:
func(arg1, arg2);
现在func
可以稍后使用参数执行此函数。
让我们看一个如何在bind
基于类的 React 组件的帮助下使用函数的经典示例:
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
counter: 1
};
}
handleCode() {
console.log("HANDLE CODE THIS = ", this.state);
}
render() {
return <button onClick={this.handleCode}>Click Me</button>;
}
}
考虑上面的 App 组件。它构成以下内容:
constructor
是一个被称为类并使用new
关键字实例化的函数。render
是一个执行/渲染 JSX 代码的函数。handleCode
是一个记录组件状态的类方法。如果我们单击该Click Me
按钮,则会收到一条错误消息:Cannot read properties of undefined (reading 'state')
。
你有没有想过为什么会出现这个问题?🤔🤔
您可能期望我们应该能够访问类的状态,因为handleCode
它是一个类方法。但这里有一个问题:
this
里面的handleCode
和类的不一样this
。this
是一个具有非静态类方法作为其属性的常规对象。但是this
里面handleCode
会指不同的上下文。this
在这种情况下, 的价值取决于从哪里调用函数。如果您看到,handleCode
则正在调用onClick
事件。undefined
的上下文。thishandleCode
state
未定义值的属性。因此,这会导致上述错误。this
我们可以通过在方法内部提供正确的上下文来解决这个问题handleCode
。您可以使用该bind
方法执行此操作。
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
counter: 1
};
this.handleCode = this.handleCode.bind(this); //bind this function
}
handleCode() {
console.log("HANDLE CODE THIS = ", this.state);
}
render() {
return <button onClick={this.handleCode}>Click Me</button>;
}
}
将bind
创建一个新函数并将其存储在this
具有新属性的对象中handleCode
。Bind
将确保类的this
上下文应用于函数this
内部的当前handleCode
。
map
函数现在我们已经拥有了所有必要的东西,让我们从创建own
地图函数开始。让我们首先了解构建own
地图功能所需的东西。
这是map
函数的语法:
arr.map(func)
在哪里,
函数的基本功能map
很简单:
它是一个遍历数组的每个元素并应用作为参数传递的函数的函数。地图的返回类型同样是一个func
应用于每个元素的数组。
现在我们了解了需求,因此我们可以继续创建自己的map
函数。这是我们的新map
函数的代码:
function newMap(func){
let destArr = [];
const srcArrLen = this.length;
for(let i = 0; i < srcArrLen; i++){
destArr.push(func.call(this, this[i]));
}
return destArr;
}
让我们一点一点的理解上面的函数:
func
。它只不过是一个需要在数组的每个元素上调用的函数。destArr.push(func.call(this, this[i]));
destArr
func
的帮助下执行call
。这里的call
方法(如前几节所述)将使用方法中存在的对象func
的新值执行方法。thisfunc
现在让我们看看我们将如何执行我们的newMap
函数。不建议使用以下向现有原始数据类型添加新方法的方法,但为了本文的目的,我们仍然会这样做。
注意:不要在您的生产代码中遵循以下方法。这可能会损坏现有代码。
Object.defineProperty(Array.prototype, 'newMap', {
value: newMap
});
defineProperty
我们在Array.prototype
.
一旦完成,我们就可以在数组上执行新的 map 函数了。
const arr = [1,2,3];
const newArr = arr.newMap(item => item + 1);
console.log(newArr);
本文通过示例向您展示了 call、apply 和 bind 函数可以做什么。
所以简单说一下这些功能:
this
调用函数中存在的关键字的上下文的函数。apply
您可以执行带有参数数组的函数,并且call
您可以执行相同的函数,但参数通过逗号传播。感谢您的阅读!
来源:https ://www.freecodecamp.org/news/understand-call-apply-and-bind-in-javascript-with-examples/
1622207074
Who invented JavaScript, how it works, as we have given information about Programming language in our previous article ( What is PHP ), but today we will talk about what is JavaScript, why JavaScript is used The Answers to all such questions and much other information about JavaScript, you are going to get here today. Hope this information will work for you.
JavaScript language was invented by Brendan Eich in 1995. JavaScript is inspired by Java Programming Language. The first name of JavaScript was Mocha which was named by Marc Andreessen, Marc Andreessen is the founder of Netscape and in the same year Mocha was renamed LiveScript, and later in December 1995, it was renamed JavaScript which is still in trend.
JavaScript is a client-side scripting language used with HTML (Hypertext Markup Language). JavaScript is an Interpreted / Oriented language called JS in programming language JavaScript code can be run on any normal web browser. To run the code of JavaScript, we have to enable JavaScript of Web Browser. But some web browsers already have JavaScript enabled.
Today almost all websites are using it as web technology, mind is that there is maximum scope in JavaScript in the coming time, so if you want to become a programmer, then you can be very beneficial to learn JavaScript.
In JavaScript, ‘document.write‘ is used to represent a string on a browser.
<script type="text/javascript">
document.write("Hello World!");
</script>
<script type="text/javascript">
//single line comment
/* document.write("Hello"); */
</script>
#javascript #javascript code #javascript hello world #what is javascript #who invented javascript
1616670795
It is said that a digital resource a business has must be interactive in nature, so the website or the business app should be interactive. How do you make the app interactive? With the use of JavaScript.
Does your business need an interactive website or app?
Hire Dedicated JavaScript Developer from WebClues Infotech as the developer we offer is highly skilled and expert in what they do. Our developers are collaborative in nature and work with complete transparency with the customers.
The technology used to develop the overall app by the developers from WebClues Infotech is at par with the latest available technology.
Get your business app with JavaScript
For more inquiry click here https://bit.ly/31eZyDZ
Book Free Interview: https://bit.ly/3dDShFg
#hire dedicated javascript developers #hire javascript developers #top javascript developers for hire #hire javascript developer #hire a freelancer for javascript developer #hire the best javascript developers
1589255577
As a JavaScript developer of any level, you need to understand its foundational concepts and some of the new ideas that help us developing code. In this article, we are going to review 16 basic concepts. So without further ado, let’s get to it.
#javascript-interview #javascript-development #javascript-fundamental #javascript #javascript-tips
1657024200
在本文中,我将通过简单的示例来解释如何在 JavaScript 中使用 call、apply 和 bind。
我们还将实现一个示例,展示如何使用 apply 函数创建自己的地图函数。
事不宜迟,让我们开始吧
让我们更仔细地看一下我们将在这里研究的函数,以了解它们的作用。
Call是一个函数,可以帮助您更改调用函数的上下文。用外行的话来说,它可以帮助您将this
函数内部的值替换为您想要的任何值。
Apply的功能非常相似call
。唯一的区别是apply
您可以将数组作为参数列表传递。
Bind是一个函数,可帮助您创建另一个函数,稍后您可以使用提供的新上下文执行该函数this
。
现在我们将看一些调用、应用和绑定函数的基本示例。然后我们将看一个示例,我们将构建自己的函数,类似于 map 函数。
call
是一个函数,用于更改this
函数内部的值并使用提供的参数执行它。
这是call
函数的语法:
func.call(thisObj, args1, args2, ...)
在哪里,
this
对象调用的函数this
函数内部的关键字替换func
this
对象的调用函数的参数。请注意,如果您调用一个没有任何thisObj
参数的函数,那么 JavaScript 会将此属性视为一个全局对象。
现在我们已经了解了call
函数是什么的一些背景信息,让我们从通过一些示例更详细地了解它开始。
考虑下面的例子。它由 3 个类组成 - Car
、Brand1
和Brand2
。
function Car(type, fuelType){
this.type = type;
this.fuelType = fuelType;
}
function setBrand(brand){
Car.call(this, "convertible", "petrol");
this.brand = brand;
console.log(`Car details = `, this);
}
function definePrice(price){
Car.call(this, "convertible", "diesel");
this.price = price;
console.log(`Car details = `, this);
}
const newBrand = new setBrand('Brand1');
const newCarPrice = new definePrice(100000);
如果你仔细看,你会发现我们使用call
函数调用了Car
两次函数。首先,在函数中setBrand
,然后在definePrice
函数中。
在这两个函数中,我们使用表示各自函数本身的对象来调用Car
函数。this
例如,在内部setBrand
,我们使用属于其上下文Car
的对象调用函数。this
情况与definePrice
.
考虑下面的例子:
const newEntity = (obj) => console.log(obj);
function mountEntity(){
this.entity = newEntity;
console.log(`Entity ${this.entity} is mounted on ${this}`);
}
mountEntity.call();
在这个例子中,我们调用了mountEntity
没有thisObj
参数的函数。在这种情况下,JavaScript 指的是全局对象。
该Apply
函数与函数非常相似Call
。call
和之间的唯一区别apply
是参数传递方式的不同。
在apply
, arguments 中,您可以将参数作为数组文字或新数组对象传递。
这是apply
函数的语法:
func.apply(thisObj, argumentsArray);
在哪里,
this
对象调用的函数this
函数内部的关键字替换func
正如您在上面看到的,该apply
函数具有不同类型的语法。
第一种语法很简单。您可以传入一个参数数组,如下所示:
func.apply(thisObj, [args1, args2, ...]);
第二种语法是我们可以将新数组对象传递给它的地方:
func.apply(thisObj, new Array(args1, args2));
第三种语法是我们可以传入 arguments 关键字的地方:
func.apply(thisObj, arguments);
arguments是函数内部可用的特殊对象。它包含传递给函数的参数值。您可以将此关键字与apply
函数一起使用以获取任意数量的任意参数。
最好的部分apply
是我们不需要关心传递给调用函数的参数数量。由于其动态性和多功能性,您可以在复杂的情况下使用它。
让我们看一下与上面相同的示例,但这次我们将使用该apply
函数。
function Car(type, fuelType){
this.type = type;
this.fuelType = fuelType;
}
function setBrand(brand){
Car.apply(this, ["convertible", "petrol"]); //Syntax with array literal
this.brand = brand;
console.log(`Car details = `, this);
}
function definePrice(price){
Car.apply(this, new Array("convertible", "diesel")); //Syntax with array object construction
this.price = price;
console.log(`Car details = `, this);
}
const newBrand = new setBrand('Brand1');
const newCarPrice = new definePrice(100000);
这是一个示例,展示了如何使用arguments
关键字:
function addUp(){
//Using arguments to capture the arbitrary number of inputs
const args = Array.from(arguments);
this.x = args.reduce((prev, curr) => prev + curr, 0);
console.log("this.x = ", this.x);
}
function driverFunc(){
const obj = {
inps: [1,2,3,4,5,6]
}
addUp.apply(obj, obj.inps);
}
driverFunc();
该函数在调用函数内部bind
创建一个具有新值的函数副本。this
这是bind
函数的语法:
func.bind(thisObj, arg1, arg2, ..., argN);
在哪里,
this
对象调用的函数this
函数内部的关键字替换func
call
函数。然后该bind
函数返回一个新函数,该函数包含一个新上下文到this
调用函数内部的变量:
func(arg1, arg2);
现在func
可以稍后使用参数执行此函数。
让我们看一个如何在bind
基于类的 React 组件的帮助下使用函数的经典示例:
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
counter: 1
};
}
handleCode() {
console.log("HANDLE CODE THIS = ", this.state);
}
render() {
return <button onClick={this.handleCode}>Click Me</button>;
}
}
考虑上面的 App 组件。它构成以下内容:
constructor
是一个被称为类并使用new
关键字实例化的函数。render
是一个执行/渲染 JSX 代码的函数。handleCode
是一个记录组件状态的类方法。如果我们单击该Click Me
按钮,则会收到一条错误消息:Cannot read properties of undefined (reading 'state')
。
你有没有想过为什么会出现这个问题?🤔🤔
您可能期望我们应该能够访问类的状态,因为handleCode
它是一个类方法。但这里有一个问题:
this
里面的handleCode
和类的不一样this
。this
是一个具有非静态类方法作为其属性的常规对象。但是this
里面handleCode
会指不同的上下文。this
在这种情况下, 的价值取决于从哪里调用函数。如果您看到,handleCode
则正在调用onClick
事件。undefined
的上下文。thishandleCode
state
未定义值的属性。因此,这会导致上述错误。this
我们可以通过在方法内部提供正确的上下文来解决这个问题handleCode
。您可以使用该bind
方法执行此操作。
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
counter: 1
};
this.handleCode = this.handleCode.bind(this); //bind this function
}
handleCode() {
console.log("HANDLE CODE THIS = ", this.state);
}
render() {
return <button onClick={this.handleCode}>Click Me</button>;
}
}
将bind
创建一个新函数并将其存储在this
具有新属性的对象中handleCode
。Bind
将确保类的this
上下文应用于函数this
内部的当前handleCode
。
map
函数现在我们已经拥有了所有必要的东西,让我们从创建own
地图函数开始。让我们首先了解构建own
地图功能所需的东西。
这是map
函数的语法:
arr.map(func)
在哪里,
函数的基本功能map
很简单:
它是一个遍历数组的每个元素并应用作为参数传递的函数的函数。地图的返回类型同样是一个func
应用于每个元素的数组。
现在我们了解了需求,因此我们可以继续创建自己的map
函数。这是我们的新map
函数的代码:
function newMap(func){
let destArr = [];
const srcArrLen = this.length;
for(let i = 0; i < srcArrLen; i++){
destArr.push(func.call(this, this[i]));
}
return destArr;
}
让我们一点一点的理解上面的函数:
func
。它只不过是一个需要在数组的每个元素上调用的函数。destArr.push(func.call(this, this[i]));
destArr
func
的帮助下执行call
。这里的call
方法(如前几节所述)将使用方法中存在的对象func
的新值执行方法。thisfunc
现在让我们看看我们将如何执行我们的newMap
函数。不建议使用以下向现有原始数据类型添加新方法的方法,但为了本文的目的,我们仍然会这样做。
注意:不要在您的生产代码中遵循以下方法。这可能会损坏现有代码。
Object.defineProperty(Array.prototype, 'newMap', {
value: newMap
});
defineProperty
我们在Array.prototype
.
一旦完成,我们就可以在数组上执行新的 map 函数了。
const arr = [1,2,3];
const newArr = arr.newMap(item => item + 1);
console.log(newArr);
本文通过示例向您展示了 call、apply 和 bind 函数可以做什么。
所以简单说一下这些功能:
this
调用函数中存在的关键字的上下文的函数。apply
您可以执行带有参数数组的函数,并且call
您可以执行相同的函数,但参数通过逗号传播。感谢您的阅读!
来源:https ://www.freecodecamp.org/news/understand-call-apply-and-bind-in-javascript-with-examples/
1626321063
PixelCrayons: Our JavaScript web development service offers you a feature-packed & dynamic web application that effectively caters to your business challenges and provide you the best RoI. Our JavaScript web development company works on all major frameworks & libraries like Angular, React, Nodejs, Vue.js, to name a few.
With 15+ years of domain expertise, we have successfully delivered 13800+ projects and have successfully garnered 6800+ happy customers with 97%+ client retention rate.
Looking for professional JavaScript web app development services? We provide custom JavaScript development services applying latest version frameworks and libraries to propel businesses to the next level. Our well-defined and manageable JS development processes are balanced between cost, time and quality along with clear communication.
Our JavaScript development companies offers you strict NDA, 100% money back guarantee and agile/DevOps approach.
#javascript development company #javascript development services #javascript web development #javascript development #javascript web development services #javascript web development company