자바 스크립트 '바인딩'방법의 사용은 무엇입니까?
bind()
JavaScript에서 무엇을 사용 합니까?
Bind는에 this
전달 된 첫 번째 매개 변수로 설정 될 새 함수를 만듭니다 bind()
.
다음 bind
은 올바른 멤버 메서드를 전달 하는 데 사용하는 방법을 보여주는 예제입니다 this
.
var Button = function(content) {
this.content = content;
};
Button.prototype.click = function() {
console.log(this.content + ' clicked');
};
var myButton = new Button('OK');
myButton.click();
var looseClick = myButton.click;
looseClick(); // not bound, 'this' is not myButton - it is the global object
var boundClick = myButton.click.bind(myButton);
boundClick(); // bound, 'this' is myButton
출력되는 내용 :
OK clicked
undefined clicked
OK clicked
첫 번째 ( this
) 매개 변수 뒤에 추가 매개 변수를 추가 할 수도 bind
있으며 해당 값을 원래 함수에 전달합니다. 나중에 바인딩 된 함수에 전달하는 모든 추가 매개 변수는 바인딩 된 매개 변수 뒤에 전달됩니다.
// Example showing binding some parameters
var sum = function(a, b) {
return a + b;
};
var add5 = sum.bind(null, 5);
console.log(add5(10));
출력되는 내용 :
15
자세한 정보와 대화 형 예제는 JavaScript 함수 바인딩 을 확인하십시오 .
업데이트 : ECMAScript 2015는 기능에 대한 지원을 추가 =>
합니다. =>
함수는 더 간결하고 this
정의 범위에서 포인터를 변경하지 않으므로 bind()
자주 사용할 필요가 없습니다 . 예를 들어 Button
첫 번째 예제 의 함수 가 click
콜백을 DOM 이벤트 에 연결하기를 원하는 경우 다음은 모두 유효한 방법입니다.
Button.prototype.hookEvent(element) {
// Use bind() to ensure 'this' is the 'this' inside click()
element.addEventListener('click', this.click.bind(this));
};
또는:
Button.prototype.hookEvent(element) {
// Use a new variable for 'this' since 'this' inside the function
// will not be the 'this' inside hookEvent()
var me = this;
element.addEventListener('click', function() { me.click() });
}
또는:
Button.prototype.hookEvent(element) {
// => functions do not change 'this', so you can use it directly
element.addEventListener('click', () => this.click());
}
가장 간단한 용도 bind()
는 호출 방법에 관계없이 특정 this
값으로 호출되는 함수를 만드는 것입니다 .
x = 9;
var module = {
x: 81,
getX: function () {
return this.x;
}
};
module.getX(); // 81
var getX = module.getX;
getX(); // 9, because in this case, "this" refers to the global object
// create a new function with 'this' bound to module
var boundGetX = getX.bind(module);
boundGetX(); // 81
자세한 내용은이 링크를 참조하십시오.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind
바인딩 허용
- "this"값을 특정 개체로 설정합니다. 때때로 이것이 의도 한 것이 아니기 때문에 이것은 매우 도움이됩니다 .
- 재사용 방법
- 기능을 카레
예를 들어 월별 클럽 회비를 공제하는 기능이 있습니다.
function getMonthlyFee(fee){
var remaining = this.total - fee;
this.total = remaining;
return this.name +' remaining balance:'+remaining;
}
이제 다른 클럽 회원에게이 기능을 재사용하려고합니다. 월 이용료는 회원마다 다릅니다.
Rachel의 잔액이 500이고 월 회비가 90이라고 가정 해 보겠습니다.
var rachel = {name:'Rachel Green', total:500};
이제 매월 그녀의 계정에서 수수료를 공제하기 위해 반복해서 사용할 수있는 함수를 만듭니다
//bind
var getRachelFee = getMonthlyFee.bind(rachel, 90);
//deduct
getRachelFee();//Rachel Green remaining balance:410
getRachelFee();//Rachel Green remaining balance:320
이제 동일한 getMonthlyFee 함수를 다른 회원 비로 다른 회원에게 사용할 수 있습니다. 예를 들어 Ross Geller는 잔액이 250 개이고 월 사용료가 25 개입니다.
var ross = {name:'Ross Geller', total:250};
//bind
var getRossFee = getMonthlyFee.bind(ross, 25);
//deduct
getRossFee(); //Ross Geller remaining balance:225
getRossFee(); //Ross Geller remaining balance:200
에서 MDN이 워드 프로세서 에 Function.prototype.bind()
:
결합 () 메소드가 호출 될 때, 새로운 함수가 호출 될 때 어떤 제공 선행 인자의 주어진 순서로 제공된 값이 그 키워드 세트가 새로운 기능을 생성한다.
그게 무슨 뜻이야?!
자, 다음과 같은 함수를 보겠습니다.
var logProp = function(prop) {
console.log(this[prop]);
};
이제 다음과 같은 개체를 살펴 보겠습니다.
var Obj = {
x : 5,
y : 10
};
다음과 같이 함수를 객체에 바인딩 할 수 있습니다.
Obj.log = logProp.bind(Obj);
이제 Obj.log
코드의 어느 곳에서나 실행할 수 있습니다.
Obj.log('x'); // Output : 5
Obj.log('y'); // Output : 10
의 값을 this
object에 바인딩했기 때문에 작동 합니다 Obj
.
정말 흥미로운 부분은에 대한 값 this
뿐만 아니라 인수에도 바인딩 할 때입니다 prop
.
Obj.logX = logProp.bind(Obj, 'x');
Obj.logY = logProp.bind(Obj, 'y');
이제 이렇게 할 수 있습니다.
Obj.logX(); // Output : 5
Obj.logY(); // Output : 10
과는 달리 Obj.log
, 우리는 통과하지 않아도 x
또는 y
우리가 우리의 결합했을 때 우리가 그 가치를 전달하기 때문에.
변수에는 지역 및 전역 범위가 있습니다. 이름이 같은 두 개의 변수가 있다고 가정 해 보겠습니다. 하나는 전역 적으로 정의되고 다른 하나는 함수 클로저 내부에 정의되어 있으며 함수 클로저 내부에있는 변수 값을 얻고 싶습니다. 이 경우이 bind () 메서드를 사용합니다. 아래의 간단한 예를 참조하십시오.
var x = 9; // this refers to global "window" object here in the browser
var person = {
x: 81,
getX: function() {
return this.x;
}
};
var y = person.getX; // It will return 9, because it will call global value of x(var x=9).
var x2 = y.bind(person); // It will return 81, because it will call local value of x, which is defined in the object called person(x=81).
document.getElementById("demo1").innerHTML = y();
document.getElementById("demo2").innerHTML = x2();
<p id="demo1">0</p>
<p id="demo2">0</p>
요약:
이 bind()
메서드는 개체를 첫 번째 인수로 사용하고 새 함수를 만듭니다. 함수가 호출 될 때 this
함수 본문 의 값은 함수에서 인수로 전달 된 객체가 bind()
됩니다.
this
어쨌든 JS에서 어떻게 작동 합니까?
this
자바 스크립트 의 값은 항상 함수가 호출되는 객체에 따라 다릅니다. 이 값은 항상 함수가 호출되는 점의 왼쪽에있는 객체를 나타냅니다 . 전역 경우이다 window
(또는 global
으로 nodeJS
). 단 call
, apply
그리고 bind
다른 바인딩이를 변경할 수 있습니다. 다음은이 키워드의 작동 방식을 보여주는 예입니다.
let obj = {
prop1: 1,
func: function () { console.log(this); }
}
obj.func(); // obj left of the dot so this refers to obj
const customFunc = obj.func; // we store the function in the customFunc obj
customFunc(); // now the object left of the dot is window,
// customFunc() is shorthand for window.customFunc()
// Therefore window will be logged
bind는 어떻게 사용됩니까?
바인딩 은 참조 할 this
고정 된 개체를 사용하여 키워드의 어려움을 극복하는 데 도움이 될 수 있습니다 this
. 예를 들면 :
var name = 'globalName';
const obj = {
name: 'myName',
sayName: function () { console.log(this.name);}
}
const say = obj.sayName; // we are merely storing the function the value of this isn't magically transferred
say(); // now because this function is executed in global scope this will refer to the global var
const boundSay = obj.sayName.bind(obj); // now the value of this is bound to the obj object
boundSay(); // Now this will refer to the name in the obj object: 'myName'
함수가 특정 this
값에 바인딩되면이 를 전달하고 다른 객체의 속성에 넣을 수도 있습니다. 의 값은 this
동일하게 유지됩니다.
I will explain bind theoretically as well as practically
bind in javascript is a method -- Function.prototype.bind . bind is a method. It is called on function prototype. This method creates a function whose body is similar to the function on which it is called but the 'this' refers to the first parameter passed to the bind method. Its syntax is
var bindedFunc = Func.bind(thisObj,optionsArg1,optionalArg2,optionalArg3,...);
Example:--
var checkRange = function(value){
if(typeof value !== "number"){
return false;
}
else {
return value >= this.minimum && value <= this.maximum;
}
}
var range = {minimum:10,maximum:20};
var boundedFunc = checkRange.bind(range); //bounded Function. this refers to range
var result = boundedFunc(15); //passing value
console.log(result) // will give true;
Creating a new Function by Binding Arguments to Values
The bind
method creates a new function from another function with one or more arguments bound to specific values, including the implicit this
argument.
Partial Application
This is an example of partial application. Normally we supply a function with all of its arguments which yields a value. This is known as function application. We are applying the function to its arguments.
A Higher Order Function (HOF)
Partial application is an example of a higher order function (HOF) because it yields a new function with a fewer number of argument.
Binding Multiple Arguments
You can use bind
to transform functions with multiple arguments into new functions.
function multiply(x, y) {
return x * y;
}
let multiplyBy10 = multiply.bind(null, 10);
console.log(multiplyBy10(5));
Converting from Instance Method to Static Function
In the most common use case, when called with one argument the bind
method will create a new function that has the this
value bound to a specific value. In effect this transforms an instance method to a static method.
function Multiplier(factor) {
this.factor = factor;
}
Multiplier.prototype.multiply = function(x) {
return this.factor * x;
}
function ApplyFunction(func, value) {
return func(value);
}
var mul = new Multiplier(5);
// Produces garbage (NaN) because multiplying "undefined" by 10
console.log(ApplyFunction(mul.multiply, 10));
// Produces expected result: 50
console.log(ApplyFunction(mul.multiply.bind(mul), 10));
Implementing a Stateful CallBack
The following example shows how using binding of this
can enable an object method to act as a callback that can easily update the state of an object.
function ButtonPressedLogger()
{
this.count = 0;
this.onPressed = function() {
this.count++;
console.log("pressed a button " + this.count + " times");
}
for (let d of document.getElementsByTagName("button"))
d.onclick = this.onPressed.bind(this);
}
new ButtonPressedLogger();
<button>press me</button>
<button>no press me</button>
The bind() method creates a new function instance whose this value is bound to the value that was passed into bind(). For example:
window.color = "red";
var o = { color: "blue" };
function sayColor(){
alert(this.color);
}
var objectSayColor = sayColor.bind(o);
objectSayColor(); //blue
Here, a new function called objectSayColor() is created from sayColor() by calling bind() and passing in the object o. The objectSayColor() function has a this value equivalent to o, so calling the function, even as a global call, results in the string “blue” being displayed.
Reference : Nicholas C. Zakas - PROFESSIONAL JAVASCRIPT® FOR WEB DEVELOPERS
As mentioned, Function.bind()
lets you specify the context that the function will execute in (that is, it lets you pass in what object the this
keyword will resolve to in the body of the function.
A couple of analogous toolkit API methods that perform a similar service:
/**
* Bind is a method inherited from Function.prototype same like call and apply
* It basically helps to bind a function to an object's context during initialisation
*
* */
window.myname = "Jineesh";
var foo = function(){
return this.myname;
};
//IE < 8 has issues with this, supported in ecmascript 5
var obj = {
myname : "John",
fn:foo.bind(window)// binds to window object
};
console.log( obj.fn() ); // Returns Jineesh
The bind function creates a new function with the same function body as the function it is calling .It is called with the this argument .why we use bind fun. : when every time a new instance is created and we have to use first initial instance then we use bind fun.We can't override the bind fun.simply it stores the initial object of the class.
setInterval(this.animate_to.bind(this), 1000/this.difference);
bind is a function which is available in java script prototype, as the name suggest bind is used to bind your function call to the context whichever you are dealing with for eg:
var rateOfInterest='4%';
var axisBank=
{
rateOfInterest:'10%',
getRateOfInterest:function()
{
return this.rateOfInterest;
}
}
axisBank.getRateOfInterest() //'10%'
let knowAxisBankInterest=axisBank.getRateOfInterest // when you want to assign the function call to a varaible we use this syntax
knowAxisBankInterest(); // you will get output as '4%' here by default the function is called wrt global context
let knowExactAxisBankInterest=knowAxisBankInterest.bind(axisBank); //so here we need bind function call to its local context
knowExactAxisBankInterest() // '10%'
참고URL : https://stackoverflow.com/questions/2236747/what-is-the-use-of-the-javascript-bind-method
'Nice programing' 카테고리의 다른 글
ELMAH가 ASP.NET MVC [HandleError] 특성과 함께 작동하도록하는 방법은 무엇입니까? (0) | 2020.10.03 |
---|---|
파이썬에서 단일 밑줄“_”변수의 목적은 무엇입니까? (0) | 2020.10.03 |
datetime을 날짜로 어떻게 변환합니까 (Python에서)? (0) | 2020.10.03 |
ISO 8601 형식의 날짜를 어떻게 구문 분석합니까? (0) | 2020.10.03 |
git diff가 호출기를 사용하지 못하도록하려면 어떻게해야합니까? (0) | 2020.10.03 |