概念:
面向对象程序设计(Objcet-oriented programming,OOP)是一种程序设计范型,同时也是一种程序开发的方法。对象指的是累的实例。它将对象作为程序的基本单元,将程序和数据封装其中,以提高软件的重要性、灵活性和扩展性。
继承、封装、多态、抽象
基于原型的继承
function foo(){
this.y = 2;
}
typeof foo.prototype;//"Object"
foo.prototype.x =1;
var obj3 = new foo();
obj3.y;//2
obj3.xl//1
obj1、obj2、obj3……继承原型链,foo函数对象继承原型链,在继承obj对象
function foo(){};
typeof foo.prototype;//"object"
foo.prototype.x =1;
var obj3 = new foo();
prototype 指向 proto 属性 x 。foo会继承prototype属性。
简单实例
function Person(name,age){
this.name = name;
this.age = age;
}
Person.prototype.LEGS_NUM = 2;//人有两个胳膊
Person.prototype.ARMS_NUM = 2;//两条腿
Person.prototype.walk = function(){
console.log(this.name + "is walking……");//每个人都可以走
};
//定义一个学生对象
function Student(name,age,className){
Person.call(this,name,age);//继承Person属性
this.className = className;//添加班级属性
}
Student.prototype = Object.create(Person.prototype);
Student.prototype.constructor = Student;
Student.prototype.hi = function(){
console.log("Hi,my name is "+this.name +",I'm"+
this.age+" years old now , and from "+
this.className+"." );
};
Student.prototype.learn = function(subject){
console.log(this.name+"is learning " +subject + " at " + this.className+".");
};
//test
var bosn = new Student('Bosn',27,'Class 3, Grade 2');
bosn.hi();//Hi,my name is Bosn,I'm 27 years old now ,and from Class 3,Grade 2;
bosn.LEGS_NUM;//2个胳膊
bosn.walk;//Bosn is walking……
bosn.learn('math');//Bosn is learning math at Class 3,Grade 2。
prototype属性
给变prototype
Student.prototype.x = 101;
bosn.x;//101
Student.prototype = {y:2};//赋值给一个新的对象
bosn.y;//undefined 修改prototype属性,对已存在的prototype属性进行修改的时候,已存在的Student.prototype的属性是不会被修改的,但是会对后续new出来的新对象中的prototype属性进行修改,下面的nunnly的y的属性值就是2;
bosn,x;//101
var nunnly = new Student('Nummly',3,'Class LOL KengB');
nunnly.x;//undefined
nunnly.y;//2
内置构造器的prototype
Object.prototype.x = 1;
var obj = {};
obj.x;//1
for(var key in obj){
console.log('result:'+key);//retrun:x
}
//ES5 IE9+
Object.defineProperty(Object.prototype,'x',{writable:true,value:1});//设置writable:true key的值就是不存在了
var obj = {};
obj.x;//1
for(var key in obj ){
console.log("result:"+key);//nothing output here
}
创建对象-new / 原型链
function foo(){};
foo.prototype.z =3;
var obj = new foo();
obj.y = 2;
obj.x = 1;
obj.z;//3;
obj.x;//1
obj.y;//2
typeof obj.toString;//function
'z' in obj;//true
obj.hasOwnProperty('z');//false
左边对象 inftanceof 一般是函数对象
[1,2] intanceof Array === true;
new Object() intanceof Array ===false;
intanceof 比对的是 对象中的prototype 如果有,则返回true
注意:不同window和iframe间的对象类型检测不能使用instanceof
实现继承的方式
function Person(){
}
functon Student(){
}
Student.prototype = Person.prototype;//1 改写Student.prototype的同时也修改了Person.prototype的属性值,这种方法不可取
Student.prototype = new Person();//2 也不是很理想
Student.prototype = Object.creat(Person.prototype);//3 这种方法是最好,ES5 之后支持的
Student.prototype.constructor = Person;
//下面函数实现了Student.prototype = Object.creat(Person.prototype);的方式
if(!Object.create){
Object.create = function(proto){
function F(){};
F.prototype = proto;
return new F;
};
}