javascript-tutorial / javascript-tutorial/en.javascript.info

Proxy and Reflect Article — Arrow Functions or `this` in Class constructor

Đang mở
#2,904 0 bình luận 1 reaction 0 người được giao Xem trên GitHub

Chưa có ai nhận issue này.

Ngôn ngữ chính
HTML
Star
25.5k
Fork
4k
Chỉ số merge pull request
Không có pull request nào được merge trong 30 ngày

Mô tả

**Source:** https://javascript.info/proxy
**Date Accessed:** 1 March 2022

A serious limitation in ES6 Proxy is the inability to proxy internal use of the `this` context inside a class. In the password example, if we use a class, then the differences in behaviour from using an arrow function vs a method is clear:

```ts

class User {

name = "John";
_password = "***";

checkPassword(value: string) {
return value === this._password;
}

checkPassword2 = (value: string) => {
return value === this._password;
}
};

const user = new Proxy(new User(), {

get(target: any, prop: string) {

if (prop.startsWith('_')) {
throw new Error("Access denied");
}
let value = target[prop];

// Commenting out the workaround
return value; // (typeof value === 'function') ? value.bind(target) : value; // (*)
},
});

console.log(user.checkPassword2('***')); // Arrow function works without the workaround because `this` is the internal context
console.log(user.checkPassword('***')); // Method fails with `Access denied` as expected

```

The point here is that if your class passes `this` somewhere in the constructor then that `this` cannot be proxied. This is a significant limitation of Proxy and should probably be mentioned in the article.

A good write up BTW.

Thanks

Hướng dẫn đóng góp

Chưa lập chỉ mục được hướng dẫn đóng góp cho kho mã nguồn này

Bắt đầu từ đâu

  1. Đọc hết issue, rồi đọc hướng dẫn đóng góp của dự án.
  2. Bình luận trên issue rằng bạn sẽ nhận — tránh hai người làm cùng một việc.
  3. Fork repository và làm thay đổi trên một nhánh.
  4. Mở pull request có tham chiếu số hiệu của issue.

Hướng nghiên cứu

Bắt đầu với bài viết về Proxy tại https://javascript.info/proxy và xem lại ví dụ về mật khẩu cùng với hành vi đã được báo cáo của class và arrow function. Cập nhật bài viết để giải thích hạn chế liên quan đến việc sử dụng this bên trong và việc truy cập qua Proxy; công việc được xem là hoàn tất khi sự khác biệt và bối cảnh của giải pháp thay thế được ghi lại chính xác.

Do mô hình lập chỉ mục viết ra từ nội dung của issue.

Đánh giá

Công nghệ
javascript
Lĩnh vực
documentation
Loại issue
Tài liệu
Độ khó
2/5
Thời gian dự kiến
1-3 giờ
Mức độ hoạt động
Đình trệ
Độ rõ ràng
Đặc tả rõ ràng
Mức phù hợp với người mới
45/100

Nhận issue mới trong hộp thư của bạn

Bản tóm tắt ngắn những issue GitHub phù hợp với người mới.