javascript 创建对象

看了w3school的关于定于对象这个部分的内容。感觉写的很好。

自己写些东西做下小结:

<script>
	<!--
	//工厂方式
	var playerMsg = function(){
		alert("Name:"+this.name+"  Nation:"+this.nation+"  Club:"+this.club);
	}
	var playerFactory = function(name,nation,club){
		var player = new Object();
		player.name = name;
		player.nation = nation;
		player.club = club;
		player.playerMsg = playerMsg;
		return player;
	}
	var player1 = playerFactory("Kuyt","Netherlands","Liverpool");
	player1.playerMsg();
	//构造函数方式
	var Player = function(name,nation,club){
		this.name = name;
		this.nation = nation;
		this.club = club;
		this.playerMsg = playerMsg;
	}
	var player2 = new Player("Suarez","Uruguay","Liverpool");
	player2.playerMsg();
	//原型方式
	var ProPlayer = function(){};
	ProPlayer.prototype.name = "Lucas";
	ProPlayer.prototype.nation = "Brazil";
	ProPlayer.prototype.club = "Liverpool";
	ProPlayer.prototype.playerMsg = playerMsg;
	var player3 = new ProPlayer();
	player3.playerMsg();
	//构造方式+原型方式
	var PlayerConstructor = function(name,nation,club){
		this.name = name;
		this.nation = nation;
		this.club = club;
	}
	PlayerConstructor.prototype.playerMsg = playerMsg;
	var player4 = new PlayerConstructor("Adam","Scotland","Liverpool");
	player4.playerMsg();
	//动态原型方式
	var PlayerDynamic = function(name,nation,club){
		this.name = name;
		this.nation = nation;
		this.club = club;
		if(typeof PlayerDynamic_initialized == "undefined"){
			PlayerDynamic.prototype.playerMsg = playerMsg;
			PlayerDynamic._initialized = true;
		}
	}
	var player5 = new PlayerDynamic("Gerrard","England","Liverpool");
	player5.playerMsg();
	-->
</script>



你可能感兴趣的:(JavaScript,function,object)