JS的面向对象与原型

∥☆過路亽.° 提交于 2019-11-26 12:49:09
const yoshi = { skulk: true };
const hattori = { sneak: true };
const kuma = { creep: true }; ⇽--- 创建3个带有属性的对象
assert("skulk" in yoshi, "Yoshi can skulk");
assert(!("sneak" in yoshi)), "Yoshi cannot sneak");
assert(!("creep" in yoshi)), "Yoshi cannot creep"); ⇽--- yoshi对象只能访问自身的属性skulk
Object.setPrototypeOf(yoshi, hattori); ⇽--- Object. setProto-typeOf方法, 将对象hattori设置为yoshi对象的原型
assert("sneak" in yoshi, "Yoshi can now sneak"); ⇽--- 通过将hattori对象设置为yoshi对象的原型, 现在yoshi可以访问hattori对象的属性
assert(!("creep" in hattori)), "Hattori cannot creep"); ⇽--- 目前hattori对象还不具有属性creep
Object.setPrototypeOf(hattori, kuma); ⇽--- 将kuma对象设置为hattori对象的原型
assert("creep" in hattori, "Hattori can now creep"); ⇽--- 现在hattori对象可以访问属性creep
assert("creep" in yoshi, "Yoshi can also creep"); ⇽--- 通过将hattori对象设置为yoshi对象的原型, 现在yoshi对象也可以访问属性creep

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!