我正在为学校做一些JavaScript练习,8号确实让我难过。
以下是原始的完整练习:
/*
* @function {Object} Person
* @param string name
*/
function Person(name) {
// Todo: Complete the function
}
var Mike = Person('John Doe');
var Bob = Person('John Doe');
var Worker = Person('John Doe');
/*
* Directions Part 1:
* - Update the Person function so the below statements don't generate any errors
*/
Mike.setName('Mike'); // name setter
Mike.getName(); // name getter
/*
* Directions Part 2:
* - Update the Person function so the below statements don't generate any errors
*/
Bob.name('Bob'); // name setter
Bob.name(); // name getter
/*
* Directions part 3:
* - Update the Person function so the below statements don't generate any errors
*
*/
Worker.setName('Kevin'); // name setter
Worker.profession('Programmer'); // profession setter
Worker.profession(); // profession getter
Worker.introduce(); // Calling this method, the Person will introduce themselves with their name and profession.
我认为我的一部分困惑是我不太明白它对我的要求。另一部分是我不熟悉这种编码风格,因为我通常不会有像这样的浮动语句。
我认为最终的结果应该是给出名称和专业,但我看不出一条通过这种方式完成它的路径。
答案 0 :(得分:0)
它是这样的:
//<![CDATA[
/* external.js */
var doc, bod, I, Person, old = onload; // for use on other loads
onload = function(){
if(old)old(); // change old var name if using technique on other pages
doc = document; bod = doc.body;
I = function(id){
return doc.getElementById(id);
}
Person = function(last, first, middle, job){
this.first = first; this.middle = middle; this.last = last; this.job = job;
this.firstName = function(first){
if(first === undefined){
return this.first;
}
this.first = first;
return this;
}
this.middleName = function(middle){
if(middle === undefined){
return this.middle;
}
this.middle = middle;
return this;
}
this.lastName = function(last){
if(last === undefined){
return this.last;
}
this.last = last;
return this;
}
this.profession = function(profession){
if(profession === undefined){
return this.job;
}
this.job = profession;
return this;
}
}
var out = I('out'), newbie = new Person;
newbie.firstName('Bob').lastName('Smith').profession('plummer');
out.innerHTML = newbie.lastName()+', '+newbie.firstName()+'; profession:'+newbie.profession();
/* you wouldn't need to use empty methods, with this design though
out.innerHTML = newbie.last+', '+newbie.first+'; profession:'+newbie.job;
would also work
*/
}
//]]>
&#13;
/* external.css */
html,body{
padding:0; margin:0;
}
body{
background:#000; overflow-y:scroll;
}
.main{
width:936px; background:#ccc; padding:20px; margin:0 auto;
}
#out{
background:#fff; padding:10px;
}
&#13;
<!DOCTYPE html>
<html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en' lang='en'>
<head>
<meta http-equiv='content-type' content='text/html;charset=utf-8' />
<meta name='viewport' content='width=device-width' />
<title>test</title>
<link type='text/css' rel='stylesheet' href='external.css' />
<script type='text/javascript' src='external.js'></script>
</head>
<body>
<div class='main'>
<div id='out'></div>
</div>
</body>
</html>
&#13;