继承有什么作用?

  • 创造新对象的时候无需重复写一些共有的属性,new的时候会继承给新对象。
  • 继承后,共有的属性和方法是共用的,避免浪费大量的资源。
  • 也方便对一些具有相同特性的对象进行统一修改。

常见的创建对象的方式主要有以下几种

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// 方法1 用直接定义object的方法
var obj1={
name:'keliangyong',
age:25
};

// 方法2 用函数创造的方法 参数传递进去 把obj return出来
function creatObj(name,age){
var obj={
name:name,
age:age
};
return obj;
}
var obj2=creatObj('keliangyong',25);

// 方法3 用构造函数的方法new一个对象
function CreatObj(name,age){
this.name=name;
this.age=age;
}
var obj3 = new CreatObj('keliangyong',25);

Object.create 在继承中的使用

Obj.create(复制目标[,额外属性/值]),创建一个拥有指定原型和若干指定属性的对象。
当我有一个构造函数Person,现在想在Person的基础上做一个新的构造函数Student,Person有的我想让Student也有,同时我自己再去给Student加新的属性。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// 初始定义
function Person(name, sex){
this.name = name;
this.sex = sex;
}
Person.prototype.printName=function(){
console.log(this.name);
}
function Student(name, sex, grade){
Person.call(this, name, sex);
this.grade=grade;
}
// 方法一 new创建法
Student.prototype = new Person; //这样Student的原型中就有Person的所有东西了 但是有很多奇怪的东子也放进去了;比如多了name:undefind,sex:undefined 强迫症表示很难受 想要个干干净净的原型
var s1 = new Student('小柯', '男', '大四');
// 方法二 Object.creat创建法
Student.prototype = Object.create(Person.prototype); // OK 完成 完美
var s1 = new Student('小柯', '男', '大四');

hasOwnProperty简介

hasOwnProperty可以用来判断一个属性是不是这个对象自身所有的,格式obj.hasOwnProperty(prop),如果是自身所有就会返回true,若不是自身所有而是继承来的话就会返回false.

Object.create的 polyfill的实现

// 以下是参考了MDN中关于Onject.create的Polyfill写法
Object.copy=function(proto){
  if(typeof proto !== 'object'){
    throw TypeError('Object prototype may only be an Object or null');
  }
  function Example(){};       // 新建一个空构造函数 
  Example.prototype=proto;   // 考虑到作为原型,所以肯定都是引用类型 直接赋值指向
  var obj = new Example();  // 因为最终返回的是原型对象
  Example.prototype=null;
  if(arguments.length>1){    // 如果参数大于1 说明有附加属性需加入
    for(var prop in arguments[1]){
      if(proto.hasOwnProperty(prop)){   // Object.create要求此处仅自身拥有的可枚举属性才有效
        obj[prop]=arguments[1][prop];   // 所以就用hasOwnProperty来判断。
      }
    }
  }
  return obj;
}

通过call去实现已有构造函数特性的复制

function Person(name, sex){
    this.name = name;
    this.sex = sex;
}
function Male(name, sex, age){
    Person.call(this, name, sex);   //把当前环境作为Person函数的this去执行 在new Male时新对象就成了Person中的this指向
    this.age = age;
}

已有一个构造函数,用继承特性在此基础上创造一个新的构造函数

//补全代码,实现继承 (难度:****)
function Person(name, sex){
  this.name=name;
  this.sex=sex;
}

Person.prototype.getName = function(){
  return this.name;
};    

function Male(name, sex, age){
 Person.call(this,name,age);
 this.age=age;
}

Male.prototype=Object.create(Person.prototype);

Male.prototype.printName = function(){
  console.log(this.getName());
};

Male.prototype.getAge = function(){
  return this.age;
};

var ruoyu = new Male('若愚', '男', 27);
ruoyu.printName();