有关原型的学习

今天开始学高级的部分,感觉还是蛮…复杂的。对我来说,其实理解会用自然可以了,学习得越多自然就会对复杂的概念有所了解。
先贴一部分今天上课时的代码:

    function Style(btnId, divId, bgColor,color) {
        this.bgColor = bgColor;
        this.color = color;
        this.btnId = document.getElementById(btnId);
        this.divId = document.getElementById(divId);
        this.height;
    }
    Style.prototype.init = function () {
        console.log(this);//指向的实例对象
        var that = this;
        //函数嵌套的时候,this会发生指向变化
        //可以把外面的this存到变量里使用
        this.btnId.onclick = function () {
            that.divId.style.backgroundColor = that.bgColor;
            that.divId.style.color = that.color;
        }
    }
    var myStyle = new Style('btn', 'box', 'red','yellow');
    myStyle.init();//谁调用this指谁
    console.dir(myStyle);
    console.dir(Style);

另外也贴一张图:
这里写图片描述
利用这种模式创建对象就会有如上图所示的关系,在上面的代码里,构造函数为:

    function Style(btnId, divId, bgColor,color) {
        this.bgColor = bgColor;
        this.color = color;
        this.btnId = document.getElementById(btnId);
        this.divId = document.getElementById(divId);
        this.height;
    }

原型对象为:

    Style.prototype.init = function () {
        console.log(this);//指向的实例对象
        var that = this;
        //函数嵌套的时候,this会发生指向变化
        //可以把外面的this存到变量里使用
        this.btnId.onclick = function () {
            that.divId.style.backgroundColor = that.bgColor;
            that.divId.style.color = that.color;
        }
    }

实例对象为:

    var myStyle = new Style('btn', 'box', 'red','yellow');

这三个东西是彼此相互关联的,构造函数被创建时,会有一个prototype属性,指向原型对象。而原型对象中的constructor属性又会指回构造函数,实例对象中的prototype也会指向原型对象。
利用原型对象的话一反面可以“节省内存”,如果说按基础学的对象去创建的话,创建100个 人对象,这100个人都会“吃东西”,那么实际运行的时候,“吃东西”会有100个相同的方法被创建,而用原型来解决的话,这100个人所用的就是同一个方法。日常编写简单例子的时候用基础的语法其实还方便一些,但是老师告诉我们做复杂的项目的话就最好用原型。

猜你喜欢

转载自blog.csdn.net/qq_42926749/article/details/81635036