1 OOP概念
面向对象程序设计(Object-oriented programming,缩写:OOP)是一种程序设计范型,同时也是一种程序开发的方法。对象指的是类的实例。它将对象作为程序的基本单元,将程序和数据封装在其中,以提高软件的重用性、灵活性和扩展性。
重要概念:继承 封转 多态 抽象
2 继承
继承的关键语句 使用Object.create创建一个空对象,其原型指向Person的原型
Student.prototype = Object.create(Person.prototype);
Student.prototype.constructor = Student;//更改Student的构造器的名字
function Person(name,age){
this.name = name;
this.age = age;
}
Person.prototype.hi = function(){
console.log("Hi,my name is"+ this.name)
}
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);
this.className = className;
}
//继承的关键语句 使用Object.create创建一个空对象,其原型指向Person的原型
Student.prototype = Object.create(Person.prototype);
Student.prototype.constructor = Student;//更改Student的构造器的名字
Student.prototype.hi = function(){
console.log("Hi! I'm "+this.name+". I'm from "+this.className);
}
Student.prototype.learn = function(subject){
console.log(this.name+" is learing "+subject);
}
var cindy = new Student('Cindy',22,'class1');
cindy.hi(); //Hi! I'm Cindy. I'm from class1
cindy.learn('JS'); //Cindy is learing JS
//Student.prototype.constrcutor=Person; 等价于下面的语句
if(!Object.create){
Object.create=function(proto){
function F(){}
F.prototype=proto;
return new F;
}
}
3 prototype属性
- 改变原型上的属性 ,对应的对象的访问该属性时也会改变(可用于共享变量和函数)
- 内置构造器的prototype 比如Object.prototype
4 instanceof
obj instanceof Array 判断obj对象的原型链中是否有Array构造器的prototype属性
// instanceOf
[1,2] instanceof Array === true;
new Object() instanceof Array === false
注意:不同window或iframe间的对象检测不能使用instanceof
5 实现继承的方式
function Person(){
}
function Student(){
}
Student.prototype = new Person(); // 继承方式1
Student.prototype = Object.create(Person.prototype);// 继承方式2
Student.prototype.constructor = Student;
console.log(Student.prototype.constructor);
// 模拟Object.create()方法
if(!Object.create){
Object.create=function(proto){
function F(){}
F.prototype=proto;
return new F;
}
}