js 对象、原型

var Obj={
	name:'Hello',
	me:function() {
		alert(this.name);
	}
  }
  Obj.me();
  Obj.name="xxd";
  Obj.me();
  function speak(line) {
	alert("speak:"+this.name+","+line);
  }
  /**Function.proprety.apply函数有两个参数,第一个是this,第二个是arguments**/
  speak.apply(null,["sxxx"]);
  /**也有个call函数,只是第二个参数不是数组**/
  speak.call(null,"sxxx");
  /**构造函数方式创建对象**/
  /**习惯上构造函数的首字母要大写,以便区别于一般函数**/
  function Rabbit(adjective) {
	this.adjective = adjective;
	this.speak = function(line) {
		alert("speak:"+this.adjective);
	}
  }
 var killerRabbit = new Rabbit("killer");
 killerRabbit.speak("GXXX");
 /**其实也可以这样**/
 function makeRabbit(adjective) {
	return {
		adjective:adjective,
		speak:function(line){/****/}
	};
 }
 debugger;
 var blackRabbit = makeRabbit("black");
 /**但是两种方式还是有区别的,new的方式使用了原型**/
 /**killerRabbit有个属性constructor,它指向Rabbit函数,blackRabbit也有这么一个属性,但它指向Object函数**/
 /**输入{}相当于new Object()**/
 /**定义的每一个函数都会自动获取一个prototype属性,该属性拥有一个对象---该函数的原型**/
 /**该原型有一个constructor属性,反指向其当前所属的函数 **/
 /**虽然对象俗话可以共享其原型对象的属性,但是这种共享是单向。因此,原型的属性影响对象,改变对象却永远不会影响到原型**/
 /**准确的规则:查询一个属性值的时候,首先查询对象自身的所有属性,如果没有则查找该对象的原型,如果再没有就查找原型的原型,一次类推**/
 /**因此,可以重载属性。如:**/
 Rabbit.prototype.teeth = "why";//这是原型上的属性
 alert(killerRabbit.teeth);
 Rabbit.teeth = "that";//不起作用
 alert(killerRabbit.teeth);
 killerRabbit.teeth = "this is true";
 alert(killerRabbit.teeth);



你可能感兴趣的:(js 对象、原型)