☰
JavaScript专项算法题(5):面向对象
2026/10/21 3:13:37 网站建设 项目流程

>>> ORIGIN全文地址:JavaScript专项算法题(5):面向对象

推荐:编程鼠标·电竞鼠标

面向对象

使用实义化的对象

挑战1/1 makePerson

问题:

构建一个称为makePerson的接受两个参数(name和age)的函数,返回一个对象。此函数会:

  1. 创建一个空对象;
  2. 给空对象一个键名为name的属性,键值为输入函数的name参数的值;
  3. 给空对象一个键名为age的属性,键值为输入函数的age参数的值;
  4. 返回对象。

题解:

/**************************************************************** WORKING WITH OBJECT LITERALS ****************************************************************//*** CHALLENGE 1 of 1 ***/functionmakePerson(name,age){// add code hereconstinnerObj={};innerObj["name"]=name;innerObj["age"]=age;returninnerObj;}constvicky=makePerson("Vicky",24);/********* Uncomment these lines to test your work! *********/console.log(vicky.name);// -> Logs 'Vicky'console.log(vicky.age);// -> Logs 24

使用Object.create

挑战1/3 personStore

问题:

在personStore对象内,创建greet属性,其值为一个打印“hello”的函数。

题解:

/**************************************************************** USING OBJECT.CREATE ****************************************************************//*** CHALLENGE 1 of 3 ***/constpersonStore={// add code heregreet:function(){console.log("hello");},};/********* Uncomment this line to test your work! *********/personStore.greet();// -> Logs 'hello'
挑战2/3 personFromPersonStore

问题:

构建personFromPersonStore函数,接受的参数为name和age。当被调用时,此函数会被通过Object.create方法在personStore对象上创建person对象。

题解:

/*** CHALLENGE 2 of 3 ***/functionpersonFromPersonStore(name,age){// add code hereconstinnerObj=Object.create(personStore);innerObj["name"]=name;innerObj["age"]=age;returninnerObj;}constsandra=personFromPersonStore("Sandra",26);// /********* Uncomment these lines to test your work! *********/console.log(sandra.name);// -> Logs 'Sandra'console.log(sandra.age);//-> Logs 26sandra.greet

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询