Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

js 原型与继承 tokobin手撕原型继承 #44

Open
0xtokobin opened this issue Feb 20, 2023 · 0 comments
Open

js 原型与继承 tokobin手撕原型继承 #44

0xtokobin opened this issue Feb 20, 2023 · 0 comments
Labels

Comments

@0xtokobin
Copy link
Collaborator

0xtokobin commented Feb 20, 2023

原型就是js的隐藏对象属性 prototype 可以赋值到其原型中 然后就可以查找到

增删对原型无效 写/删除操作直接在对象上进行,它们不使用原型(假设它是数据属性,不是 setter)

看以下代码:

let animal = {
eats: true
};
let rabbit = {
jumps: true
};

rabbit.proto = animal; // 设置 rabbit.[[Prototype]] = animal

// 现在这两个属性我们都能在 rabbit 中找到:

alert( rabbit.eats ); // true (**)

alert( rabbit.jumps ); // true

当 alert 试图读取 rabbit.eats (**) 时,因为它不存在于 rabbit 中,所以 JavaScript 会顺着 [[Prototype]] 引用,在 animal 中查找(自下而上):

image

在这儿我们可以说 "animal 是 rabbit 的原型",或者说 "rabbit 的原型是从 animal 继承而来的"。

因此,如果 animal 有许多有用的属性和方法,那么它们将自动地变为在 rabbit 中可用。这种属性被称为“继承”。

如果我们在 animal 中有一个方法,它可以在 rabbit 中被调用:

image

原型链也可以套 很长

let animal = {
eats: true,
walk() {
alert("Animal walk");
}
};

let rabbit = {
jumps: true,
proto: animal
};

let longEar = {
earLength: 10,
proto: rabbit
};

// walk 是通过原型链获得的
longEar.walk(); // Animal walk

alert(longEar.jumps); // true(从 rabbit)

image

this不受原型影响

for in 也可以继承

@0xtokobin 0xtokobin added the es6 label Feb 20, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant