JavaScript Function bind()
- الصفحة السابقة JS Function Apply
- الصفحة التالية JS اللفة
استعارة الدالة (Function Borrowing)
من خلال استخدام bind()، يمكن لشخصية واحدة استعارة طريقة من شخصية أخرى.
في هذا المثال، تم إنشاء 2 شخصيات (person و member).
استعارة شخصية member لطريقة fullname من شخصية person:
مثال
const person = { firstName:\"Bill\", lastName: "Gates", fullName: function () { return this.firstName + \" \" + this.lastName; } } const member = { firstName:\"Hege\", lastName: "Nilsen", } let fullName = person.fullName.bind(member);
حفظ this
في بعض الأحيان، قد تحتاج إلى استخدام bind() لمنع فقدان this.
في هذا المثال، لدى شخصية person طريقة display. في طريقة display،this يعني شخصية person:
مثال
const person = { firstName:\"Bill\", lastName: "Gates", display: function () { let x = document.getElementById("demo"); x.innerHTML = this.firstName + " " + this.lastName; } } person.display();
عندما يتم استخدام الدالة كإ回调this سيتم فقدانه.
هذا المثال سيحاول عرض اسم الشخص بعد 3 ثوانٍ، لكنه سيظهر undefined:
مثال
const person = { firstName:\"Bill\", lastName: "Gates", display: function () { let x = document.getElementById("demo"); x.innerHTML = this.firstName + " " + this.lastName; } } setTimeout(person.display, 3000);
حل bind() هذا المشكلة.
في هذا المثال، يتم استخدام bind() لربط person.display إلى person.
هذا المثال سيظهر اسم الشخص بعد 3 ثوانٍ:
مثال
const person = { firstName:\"Bill\", lastName: "Gates", display: function () { let x = document.getElementById("demo"); x.innerHTML = this.firstName + " " + this.lastName; } } let display = person.display.bind(person); setTimeout(display, 3000);
ما هو this؟
في JavaScript،this
المرجع الكلمة المفتاحيةعنصر.
مرتبطأيالعنصر يعتمد على طريقة التسمية (الاستخدام أو التسمية).
اعتمادًا على طريقة الاستخدام، الكلمة المفتاحية this
مرتبط بالعناصر المختلفة:
- في طرق العنصر،
this
مرتبط بالعنصر. - عند استخدامه بشكل منفرد،
this
مرتبطعنصر عالمي. - في الدالة،
this
مرتبطعنصر عالمي. - في الدالة، في الوضع الصارم،
this
هوundefined
. - في الحدث،
this
مرتبط باستقبال الأحداثعنصر. - يمكن استخدام طرق مثل call()، apply() و bind() وما إلى ذلك لتحويل
this
مرتبطأي عنصر.
ملاحظة:this
ليس متغيرًا. إنه كلمة مفتاحية. لا يمكنك تعديلها this
القيمة.
يرجى الرجوع إلى:
دليل:JavaScript this
- الصفحة السابقة JS Function Apply
- الصفحة التالية JS اللفة