Javascript 面向对象编程(二):如何生成一个对象

<script type="text/javascript">
	
	//1. 采用new 方法,构造模式,运用this和prototype
	function Cat1(name,color){
		this.name  = name;
		this.color = color;
	}
	catA = new Cat1('大黄','黄色');
	alert(catA.name); //大黄;

	Cat1.prototype.makeSound = function() {
		alert("喵喵喵" );
	};
	catA.makeSound(); //喵喵喵

	//2 .采用Object.create()方法
	var Cat2 = {
		name:'大黑',
		color:'黑色',
		makeSound : function(){
			alert('sb');
		}
	}

	var catB = Object.create(Cat2);
	alert(catB.name); //大黑
	catB.makeSound(); // sb

	//3 .采用 "极简主义法"(minimalist approach)
	//3.1. 封装。首先,它也是用一个对象模拟"类"。在这个类里面,定义一个构造函数createNew(),用来生成实例。
	var Dog = {
		createNew:function(){
			var dog = {};
			dog.color = '黄';
			dog.name  = '狗';
			dog.makeSound = function(){
				alert('汪汪汪');
			}
			return dog;
		}
	}

	var dog1 = Dog.createNew();
	alert(dog1.name); //狗
	dog1.makeSound(); //汪汪汪

	//3.2. 继承 。让一个类继承另一个类,实现起来很方便。只要在前者的createNew()方法中,调用后者的createNew()方法即可
	var Animal = {
		createNew:function(){
			var animal = {};
			animal.sleep = function(){alert('睡觉')};
			return animal;
		}
	}

	var Pig = {
		createNew:function(){
			var pig = Animal.createNew();
			pig.name = '猪';
			return pig;
		}
	}
	var pig1 = Pig.createNew();
	alert(pig1.name); //子属性 :猪
	pig1.sleep();// 父方法 睡觉

	// 3.3. 私有属性和私有方法
	// 在createNew()方法中,只要不是定义在peopel对象上的方法和属性,都是私有的。
	var People = {
		createNew:function(){
			var people = {};
			people.name = '人';
			people.say = function(){alert('会说话')};
			var fly = "我会飞"; //私有属性
			var swim = function(){alert('我会游泳')}; //私有方法
			people.flying = function(){alert(fly)};
			people.swiming = function(){swim();};
			return people;
		}
	}
	var people1 = People.createNew();
	alert(people1.fly); //undefined
	people1.flying(); //我会飞
	people1.swiming(); //我会游泳

	// 3.4 数据共享
	// 有时候,我们需要所有实例对象,能够读写同一项内部数据。这个时候,只要把这个内部数据,封装在类对象的里面、createNew()方法的外面即可。
	var Car = {
		size:'15马力',
		createNew:function(){
			car = {};
			car.getSize = function(){
				alert(Car.size);
			};
			car.setSize = function(size){
				Car.size = size;
			}
			return car;
		}
	}

	var car1 = Car.createNew();
	var car2 = Car.createNew();
	car1.getSize();
	car1.setSize('300马力');
	car1.getSize(); //变了
	car2.getSize(); //也变了。

</script>

你可能感兴趣的:(JavaScript,对象)