CODEEXPLORE Telegram 4288
⚙️ یکی از اشتباهات رایج در جاوااسکریپت زمانی پیش میاد که بخوای متغیر خصوصی (Private Variable) رو با Prototype ترکیب کنی.

در متدهایی که داخل constructor تعریف میشن، متغیرهای خصوصی از طریق Closure در دسترس هستن.
اما وقتی متد رو روی prototype تعریف کنی، اون متد به scope خصوصی constructor دسترسی نداره و فقط می‌تونه از this استفاده کنه.
function MyConstructor() {
var x = "ABC";
}
MyConstructor.prototype.getX = function() {
return x;
};


اینجا getX روی prototype تعریف شده، اما به متغیر x که داخل constructor بوده دسترسی نداره؛ چون اون متغیر فقط داخل closure ساخته شده.

اما توی این مثال:
function MyConstructor() {
var x = "ABC";
this.getX = function() {
return x;
};
}


اینجا متد getX داخل constructor تعریف شده و به x دسترسی داره چون در همون scope ساخته شده.

#js #prototype
☕️Telegram | Website | Discord
❤‍🔥36🔥5😍1



tgoop.com/CodeExplore/4288
Create:
Last Update:

⚙️ یکی از اشتباهات رایج در جاوااسکریپت زمانی پیش میاد که بخوای متغیر خصوصی (Private Variable) رو با Prototype ترکیب کنی.

در متدهایی که داخل constructor تعریف میشن، متغیرهای خصوصی از طریق Closure در دسترس هستن.
اما وقتی متد رو روی prototype تعریف کنی، اون متد به scope خصوصی constructor دسترسی نداره و فقط می‌تونه از this استفاده کنه.

function MyConstructor() {
var x = "ABC";
}
MyConstructor.prototype.getX = function() {
return x;
};


اینجا getX روی prototype تعریف شده، اما به متغیر x که داخل constructor بوده دسترسی نداره؛ چون اون متغیر فقط داخل closure ساخته شده.

اما توی این مثال:
function MyConstructor() {
var x = "ABC";
this.getX = function() {
return x;
};
}


اینجا متد getX داخل constructor تعریف شده و به x دسترسی داره چون در همون scope ساخته شده.

#js #prototype
☕️Telegram | Website | Discord

BY کداکسپلور | CodeExplore


Share with your friend now:
tgoop.com/CodeExplore/4288

View MORE
Open in Telegram


Telegram News

Date: |

Co-founder of NFT renting protocol Rentable World emiliano.eth shared the group Tuesday morning on Twitter, calling out the "degenerate" community, or crypto obsessives that engage in high-risk trading. Select “New Channel” Judge Hui described Ng as inciting others to “commit a massacre” with three posts teaching people to make “toxic chlorine gas bombs,” target police stations, police quarters and the city’s metro stations. This offence was “rather serious,” the court said. As five out of seven counts were serious, Hui sentenced Ng to six years and six months in jail. The best encrypted messaging apps
from us


Telegram کداکسپلور | CodeExplore
FROM American