zoukankan      html  css  js  c++  java
  • js OOP 面向对象

    数组对象:

    数组也是对象,原型链:
    var arr = []
    typeof arr // "object"
    arr ----> Array.prototype ----> Object.prototype ----> null

    函数对象:

    函数原型链
    foo ----> Function.prototype ----> Object.prototype ----> null

    对象:

            function Student(name) {
                this.name = name || '未知';
            }
    
            // 放原型上,作为共享同一个hello,节约内存
            Student.prototype.hello = function () {
                console.log('Hello, ' + this.name + '!');
            }
    
            console.log(new Student().name);
    
            var xiaoming = new Student('小明');
            console.log(xiaoming.name); // '小明'
            xiaoming.hello(); // Hello, 小明!
    
            console.log(' _____________________ ');
    
            var xiaohong = new Student('小红');
            console.log(xiaohong.name);
            xiaohong.hello();
    
            console.log(' _____________________ ');
    
            console.log(xiaoming.hello);
            console.log(xiaohong.hello);
            console.log(xiaoming.hello === xiaohong.hello); // 共用的,所以true

    对象原型链

    xiaoming ----> Student.prototype ----> Object.prototype ----> null
    
    xiaoming ↘
    xiaohong -→ Student.prototype ----> Object.prototype ----> null
    xiaojun  ↗
    function B(name) {
            this.name = name
            this.getName = function() {
                console.log(this.name)
            }
     
            var c = 'test'
            console.log(c)
        }
     
        var b = new B('testb')      // test
        console.log(b)              // B: { name: 'testb',getName: function() {} }
        B('testc')                  // test
    View Code

    new的时候发生了什么?

    //  javascript 实际上执行的是: 
    var o = new Object()   // 生成一个新的对象b这里 可以约等于var b={}
     
    o.__proto__ = B.prototype // 这里就是函数对象中独有的prototype属性。
    // 这个独有的prototype属性包含了一个constructor属性方法,指向的就是构造函数,也就是这里的function B(name) {}
     
    B.call(o)      // tips :这里就需要注意了,因为很多同学都搞不清楚这里是什么意思。
    // 由于call的使用将这里this是指向o, 所以就可以把什么this.name/getName 强行的绑定到o上。同时,需要注意的一点就是,这里的构造函数执行科一遍,只不过是将this指向的属性和方法,都强行的给新创建的这个o对象绑定了一遍。
     
    var b = o      // 把这个o返回给了b。从而完成了var b = new B('testb')的过程

     以下复习适合新手:

    https://www.liaoxuefeng.com/wiki/1022910821149312/1023022043494624

    https://www.cnblogs.com/jiejiejy/p/7666091.html 

    prototype 和 proto 的区别 

    https://blog.csdn.net/Mean_/article/details/90779698 

    .

  • 相关阅读:
    决策树
    训练/测试
    机器学习 标准差
    pandas01
    提交参数说明
    pandas_series02
    Yarn 模式
    词云图
    软件需求与分析课堂综合测试
    课堂测试10
  • 原文地址:https://www.cnblogs.com/xiangsj/p/12327251.html
Copyright © 2011-2022 走看看