JavaScript学习总结1

 /***我是切割线 的開始***/
 
 //利用prototype属性能够加入公有属性和方法
   function myConstructor2(){
   		this.a='大灰狼';
   	};  //声明构造函数,能够使用对象字面量语法来向prototype属性中加入全部公有成员
   
    myConstructor2.prototype={
     propertyA: 'sha' ,
     propertyB: 'feng' ,
     methodA:function(){
      alert(this.propertyA);
     },
     methodB:function(){}
    }
   
   var myconstrustor=new myConstructor2(); //声明对象
    //alert(myconstrustor.methodA());
 var myconstrustor1=new myConstructor2(); //声明对象
 var myconstrustor2=new myConstructor2(); //声明对象
	alert("原型类測试结果="+(myconstrustor1.propertyB === myconstrustor2.propertyB));

	alert("构造函数測试结果="+(myconstrustor1.a === myConstructor2.a));

 /***我是切割线 的结束***/


function member(name, sex) {
  this.name = name;
  this.sex = sex;
  this.display = display;
}

function display() {
  var str = this.name + "是" + this.sex;
  document.write("<LI>" + str);
}
var papa = new member("杨宏文", "男生");
var mama = new member("黄雅玲", "女生");
var doggy = new member("奇 奇", "宠物狗");

papa.display();
mama.display();
doggy.display();

/*

*/

     

总结
     1. 
在构造函数中定义的属性。每一个实例都有一个副本,互不影响。可是在prototype上定义的属性,在全部的实例中共享同一个属性。对属性的改变会影响到全部的实例。


    
从上面总结的观点来看。假设要模拟面向对象,那么属性最好定义在构造函数中,而方法最好定义在prototye中,否则每一个实例的方法都占领一块内存,太浪费了。


     2
.从上面知道了Js中也有实例属性也有静态属性。但终于的目的是为了更好的了解Js中的继承,根据面向对象的思想,我们定义一个类,是为了实例化,使实例能够调用类中定义的属性、方法。因此能够这么说除非为了共享一个全局属性,普通情况下我们都应该定义实例属性、方法,这样类的实例就能够进行各种调用操作。承上启下,从源代码能够看出定义实例属性有2中方式,一种定义在构造函数中,一种是构造函数的prototype上,究竟应该使用哪一种呢。或者那种方式更好?

4.能够总结出几条规律:

1:当实例本身定义了属性。使用本身属性(能够使用hasOwnProperty进行推断)
2:假设实例本身未定义。就到构造函数中去找;

3:假设构造函数也没有,就到构造函数的
prototype的实例对象上去找。
4:假设
prototype的实例对象没有,就到其构造函数去找;
5:
如此反复,一直到跟对象object中,没找到就报undefined错误。



原文地址:https://www.cnblogs.com/mfrbuaa/p/5129515.html