js难点(二)封装与继承

js一切皆是对象。然而js语法里没有类,所以如果对象里面要有属性(proterty)和方法(method),就必须要用到封装。

为了实现原型对象与实例对象的相关,封装提供了2种模式,构造函数模式与原型模式。(至于工厂模式就不说啦,工作都没用到)

(一) 构造函数

    function Cat(name,color){
    this.name=name;
    this.color=color;
  }
  var cat1 = new Cat("大毛","黄色");
  var cat2 = new Cat("二毛","黑色");
  alert(cat1.name); // 大毛
  alert(cat1.color); // 黄色
    alert(cat1.constructor == Cat); //true
  alert(cat2.constructor == Cat); //true
  alert(cat1 instanceof Cat); //true
  alert(cat2 instanceof Cat); //true
(二)原型模式

 function Cat(name,color){
    this.name = name;
    this.color = color;
  }
  Cat.prototype.type = "猫科动物";
  Cat.prototype.eat = function(){alert("吃老鼠")};
   var cat1 = new Cat("大毛","黄色");
  var cat2 = new Cat("二毛","黑色");
  alert(cat1.type); // 猫科动物
  cat1.eat(); // 吃老鼠
 alert(cat1.eat == cat2.eat); //true
一般来讲,写一个实例对象,一般都是通过组合构造函数与原型的,构造函数用于定义实例属性,原型用于共享属性与定义方法。
  function Person(name, age, job) {
        this.name = name;
        this.age = age;
        this.job = job;
        this.sayName = function() {
            alert(this.name)
        }
    }
 
    Person.prototype = {
        sayJob : function() {
            console.log(this.job);
        }
    }
 
    var person1 = new Person('tj', 22 , 'fe');
继承:主要是指子类继承父类的属性以及方法

function person(name, sex){

        this.name=name;
        this.sex=sex;
}

     person.prototype.showName=function(){
           alert(this.name);
}
     person.prototype.showSex=function(){
          alert(this.sex);
}
function worker(job){
  personal.apply(this,arguments);
  this.job=job;
}
var ow=new worker('blue','男','程序员');
  ow.showName();  //blue
      ow.showsex();  //男
      ow.showjob();  //程序员














猜你喜欢

转载自blog.csdn.net/xieyixiao_123/article/details/79193432