首页 > 编程语言 > 详细

JavaScript原型与继承

时间:2017-03-15 22:39:33      阅读:163      评论:0      收藏:0      [点我收藏+]

1.构造函数其实就是一个普通函数,但是内部使用了this变量。对构造函数使用new运算符,就能生成实例,并且this变量会绑定在实例对象上。

  function Cat(name,color){
    this.name=name;
    this.color=color;
      this.type = "猫科动物";
      this.eat = function(){console.log("吃老鼠");};
  }
  var cat1 = new Cat("大毛","黄色");
  var cat2 = new Cat("二毛","黑色");
  console.log(cat1.name); // 大毛
  console.log(cat1.color); // 黄色
    //这时cat1和cat2会自动含有一个constructor属性,指向它们的构造函数。
    console.log(cat1.constructor == Cat); //true
    console.log(cat2.constructor == Cat); //true
    //instanceof运算符,验证原型对象与实例对象之间的关系。
    console.log(cat1 instanceof Cat); //true
    console.log(cat2 instanceof Cat); //true

    console.log(cat1.type); // 猫科动物
    cat1.eat(); // 吃老鼠

这样写的弊端:对于每一个实例对象,type属性和eat()方法都是一模一样的内容,每一次生成一个实例,都必须为重复的内容,多占用一些内存。这样既不环保,也缺乏效率。

console.log(cat1.eat == cat2.eat); //false

 

所以对于相同的属性和方法等,要用prototype去定义。上面的那两个公共部分应该如下写:

  Cat.prototype.type = "猫科动物";
  Cat.prototype.eat = function(){console.log("吃老鼠")}; 

此时:

console.log(cat1.eat == cat2.eat); //true

一些常用属性:

      console.log(Cat.prototype.isPrototypeOf(cat1)); //true
      console.log(Cat.prototype.isPrototypeOf(cat2)); //true

        //本地属性才为true,prototype继承的属性为false
      console.log(cat1.hasOwnProperty("name")); // true
      console.log(cat1.hasOwnProperty("type")); // false

      console.log("name" in cat1); // true
      console.log("type" in cat1); // true
        for(var prop in cat1) { //遍历属性,包括继承的
            console.log("cat1[" + prop + "]=" + cat1[prop]); 
        }

 

2.构造函数的继承

一、 构造函数绑定。使用call或apply方法,将父对象的构造函数绑定在子对象上。

   function Animal(){
    this.species = "动物";
  }
  function Cat(name,color){
    Animal.apply(this, arguments);
    this.name = name;
    this.color = color;
  }
  var cat1 = new Cat("大毛","黄色");
  console.log(cat1.species); // 动物

 

JavaScript原型与继承

原文:http://www.cnblogs.com/shen076/p/6556868.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!