markdown JavaScript - 调用,应用,绑定

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了markdown JavaScript - 调用,应用,绑定相关的知识,希望对你有一定的参考价值。

# Javascript - Call, Apply, Bind

## Call method

This object _**profile**_ doesn't have a **method** _**setName**_ and we want to use the _**setName**_ in this profile object

```js
const profile = {
  name: "John",
  age: 24
};

const setName = function(name) {
  return this.name = name;
};
```

We can use the **Call** method in **setName** function

```js
setName.call(profile, 'peter');
```

when we console.log() the profile object this is the result:

```js
console.log(profile); // {name: "peter", age: 20}
```

## Apply method

If we want to pass **multiple** parameters, or arrays, we can use the _**Apply**_ method
```js
const profile = {
  name: "John",
  age: 24
};

const setProfile = function(name, age) {
  this.name = name;
  this.age = age;
}

let params = ['peter', 30];

setProfile.apply(profile, params);

console.log(profile); // {name: "peter", age: 30}
```

## Bind method

An example of a loose method
```js
const profile = {
  name: "Jonh",
  getName() {
    return this.name;
  }
}
const getNameLoose = profile.getName;
console.log(getNameLoose()); // undefined
```

In order to find a method in an object, we may use the _**bind**_ method
```js
const profile = {
  name: "John",
  age: 24
};

const setProfile = function(name, age) {
  this.name = name;
  this.age = age;
}

const boundToProfile = setProfile.bind(profile);

console.dir(boundToProfile); 
/* 
...
[[TargetFunction]]: ƒ (name, age)
[[BoundThis]]: Object
age: 24
name: "John"
...
*/
```

It is as if the **setProfile** method is part of the object **profile**
```js
const profile = {
  name: "John",
  age: 24,
  setProfile(name, age) {
    this.name = name;
    this.age = age;
  }
};
```

And now we can call it like this
```js
boundProfile('george', 2);

console.log(profile); // {name: "george", age: 2}
```

以上是关于markdown JavaScript - 调用,应用,绑定的主要内容,如果未能解决你的问题,请参考以下文章

Javascript 将 Markdown/Textile 转换为 HTML(理想情况下,返回 Markdown/Textile)

推荐一个markdown格式转html格式的开源JavaScript库

推荐一个markdown格式转html格式的开源JavaScript库

JavaScript 如何将 HTML 转成 Markdown?

Javascript中的Markdown解析器[关闭]

javascript 仅在markdown语法中解析斜体