Skip to content

Instantly share code, notes, and snippets.

@jocoonopa
Last active December 29, 2015 01:39
Show Gist options
  • Save jocoonopa/7594400 to your computer and use it in GitHub Desktop.
Save jocoonopa/7594400 to your computer and use it in GitHub Desktop.
<!doctype html>
<html lang="zh-tw">
<head>
<meta charset="UTF-8">
<title>Javascript的奇幻物件之旅</title>
<script src="//code.jquery.com/jquery-1.9.1.js"></script>
</head>
<body>
<div>公私有屬性方法簡單介紹</div>
</body>
<script>
$(function () {
// 宣告類別
var pet = function () {
// 不能用 name當例子 , 因為function.name為 js 預設屬性
// 私有屬性
var names = 'Dog',
names2 = 'Tiger',
memberObj = {
names: 'deepFish'
};
// 這也是私有屬性 , 會蓋掉22行的 'Dog', 類別裡的私有屬性names都註解掉的話 ,
// names私有屬性會因為 Scope 變成 'Kitty'
names = 'Elephant';
// 動態( 公有 )屬性
this.names = 'Mouse';
// 動態( 公有 )屬性
pet.names = 'Cat';
// 動態( 公有 )屬性物件
this.member = {
names: 'freeBirds'
};
// 私有方法
function shownames () {
// 利用閉包取得私有屬性
console.log( '內部調用私有屬性: ' + names );
// 類別屬性
console.log( '內部調用類別屬性: ' + pet.names );
// 公有屬性, 要透過實體化物件調用
console.log( '內部調用公有屬性: ' + this.names );
// 利用閉包取得私有屬性
console.log( '內部調用私有屬性物件之屬性: ' + memberObj.names );
// 公有屬性, 要透過實體化物件調用
console.log( '內部調用公有屬性物件之屬性: ' + this.member );
}
// 公有方法調用私有方法
this.show = function() {
shownames();
};
};
// 設計上公有方法都是外部利用prototype添加 , 避免重複建立造成效能降低
pet.prototype.setnames = function ( str ) {
// 公有屬性被改掉
this.names = str;
// Kitty會被蓋掉 ( 全域變數 )
names = str;
// 類別屬性被改
pet.names = str;
// 公有屬性被改掉
Penguin.names = '直接選擇企鵝的屬性做更改';
};
// 類別實體化物件
var Penguin = new pet(),
names = 'Kitty';
// 調用公有方法
Penguin.show();
console.log( '類別屬性: ' + pet.names );
console.log( '全域變數: ' + names );
console.log( '公有屬性: ' + Penguin.names );
console.log( '私有屬性: ' + Penguin.names2 );
console.log( '公有物件屬性: ' + Penguin.member.names );
// 調用公有方法改變屬性值
Penguin.setnames( 'Jonoonopa' );
// 調用公有方法
Penguin.show();
console.log( '類別屬性: ' + pet.names );
console.log( '全域變數: ' + names );
console.log( '公有屬性: ' + Penguin.names );
console.log( '私有屬性: ' + Penguin.names2 );
console.log( '公有物件屬性: ' + Penguin.member.names);
});
</script>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment