JavaScript 使用簡略文法建立對象

來源:互聯網
上載者:User

 

<html>
<head>
<title>JavaScript 使用簡略文法建立對象</title>
<script type="text/javascript">
window.onload = function(){
AppendMembersToObject();
SimpleSyntaxToCreateObject();
}

function AppendMembersToObject()
{
var testName = "AppendMembersToObject";
WriteStart(testName);

// 建立一個對象
var person = new Object();
// 給對象添加屬性(public)
person.Name = "lipei";
person.Sex = "boy";
person.Age = "24";
// 給對象添加方法(public)
person.toString = function(){
//此處用person或this都可以,此時this指代person對象。
return str = "Name:" + this.Name + ",Sex:" + this.Sex + ",Age:" + this.Age;
}
WriteLine("person.Name : " + person.Name);
WriteLine("person.toString() : " + person.toString());

WriteEnd();

/*
根據結果可知:JavaScript 中可在對象建立後,為對象新增成員(屬性、方法等)。
*/
}

function SimpleSyntaxToCreateObject()
{
var testName = "SimpleSyntaxToCreateObject";
WriteStart(testName);

// 使用簡略文法建立對象
var computer = {
Cpu : "酷睿2P系列",
MainBoard : "華碩ER",
Keyboard : "雙飛燕",
toString : function(){
return str = "Cpu:" + this.Cpu + ",MainBoard:" + this.MainBoard + ",Keyboard:" + this.Keyboard;
}
};
WriteLine("computer.MainBoard : " + computer.MainBoard);
WriteLine("computer.toString() : " + computer.toString());

WriteEnd(testName);

/*
根據結果可知:JavaScript簡略文法可只能識別變數冒號後的類型,並據此定義變數的類型。
*/
}

/*************************Test Tools**************************/
function WriteLine(str)
{
document.write(str + "<br/>");
}

function WriteStart(str)
{
WriteLine("TEST : " + str + "<br/>");
}

function WriteEnd()
{
WriteLine("<br/><hr/>");
}
</script>
</head>
<body>
</body>
</html>

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.