4.临时构造器

来源:互联网 发布:淘宝 软件 编辑:程序博客网 时间:2024/06/07 18:18

demo:http://runjs.cn/code/akzyhyen

写在前面:在前一章基础上继续修改,红色标注为不同之处   

 console.log("我们知道第一章的时候子类修改属性的时候是不会影响到父级的,子级之间更不会互相影响,

                      因为都是通过new了后的对象赋值的!!")

    console.log("那我们也可以新建一个临时对象再赋值这里就避免了互相影响,

                      这章之后我们将会封装一个函数来实现继承")

  
   //构造函数    function Shape() {};    //添加原型    Shape.prototype.name = "Shape";    Shape.prototype.toString = function() {        return this.name;    }    //其他构造函数    function TwoDshape() {};    //不再使用new来创建对象,而是直接“引用”    var F = function() {};    F.prototype = Shape.prototype;    TwoDshape.prototype = new F();    //修改constructor指向    TwoDshape.prototype.constructor = TwoDshape;    //修改TwoDshape的属性    TwoDshape.prototype.name = "2d shape";    //第三个构造函数,和其他函数不一样的是这里有自身自带的方法属性    function Triangle(side, height) {        this.side = side;        this.height = height;    }    //不再使用new来创建对象,而是直接“引用”    var F = function() {};    F.prototype = Shape.prototype;    Triangle.prototype = new F();    Triangle.prototype.constructor = Triangle;<span style="color:#ff0000;">//A 最好这样手动修改,方便之后的判断需要</span>    //修改属性    Triangle.prototype.name = "Triangle";    Triangle.prototype.getArea = function() {        return this.side * this.height / 2;    }    //开始试验----------    var my = new Triangle(5, 10);    console.log("和上一章已经进行相同的检测")    var my = new Triangle(5, 10);    console.log(my.toString());    //my的构造函数是谁呢?    console.log("my的构造函数是谁呢?---------");    console.log(my.constructor === Triangle); //在A处我们明确把Triangle的constructor指向了Triangle    console.log("通过instanceof来主动查找实例my对象的构造函数是谁?");    console.log(my instanceof Shape); //true    console.log(my instanceof TwoDshape); //true    console.log(my instanceof Triangle); //true    console.log("通过构造函数sPrototypeOf方法来判断是否拥有相应的实例------------")    console.log(Shape.prototype.isPrototypeOf(my)); //true    console.log(TwoDshape.prototype.isPrototypeOf(my)); //true    console.log(Triangle.prototype.isPrototypeOf(my)); //true    console.log("效果和上一章一模一样,下面来的不一样的,通过hasOvenProperty()来验证是自身属性还是原型链属性")    console.log(my.hasOwnProperty('side')) //true    console.log(my.hasOwnProperty('name')) //false    console.log("再new一个子类来检测他们的属性是否互相影响")    var s = new Shape();    console.log(s.name);    console.log("可以看到Shape的name还是Shape了,修复了上一章遇到的互相影响的问题了")    console.log("我们来看一下他们的原型链")    console.log("my的原型链和my的构造函数,只是不知道为什么这里TwoDshape为false")    console.log(my.__proto__===Triangle.prototype);    console.log(my.__proto__.constructor==Triangle);    console.log(my.__proto__.__proto__==Shape.prototype);    console.log(my.__proto__.__proto__.constructor==Shape);

0 0