JS面向对象编程(二) JS中的构造函数!

JS中的构造函数是JS面向对象编程的核心,虽然ES6已经引入了Class类的概念,但是论灵活性还是构造函数更胜一筹。
一段代码,先对构造函数有基本的认识:

function Animal(name, type) {
        this.name = name;
        this.type = type;
        this.do = '';
        this.action = function () {
            switch (this.type) {
                case 'cat':
                    this.do = 'climb';
                    break;
                case 'dog':
                    this.do = 'fight';
                    break;
            }
            return this.do;
        }
    }

    var animal = new Animal('老虎','cat');
    console.log(animal.action()); //climb

表达式new,我总结出有以下四个步骤:

  1. 在构造函数中创建一个空对象。
  2. 将构造函数中的this指向该对象。
  3. 执行构造函数中的代码语句。
  4. 将填充完属性和方法的对象return。

每一个构造函数在被创建的时候,都会自动生成一个prototype属性,该属性是一个空对象,也就是该构造函数的原型。

接着上面的代码:

console.log(Animal.prototype === animal.__proto__); //true

当构造函数的实例需要一个属性时,会顺着__proto__属性向上查找构造函数的原型。

 Animal.prototype.age = 10;
    console.log(animal.age); //10
console.log(animal.__proto__.age); //10

建议:在创建构造函数时,将属性定义在函数中,方法定义在原型中。

构造函数的继承:

function A(name) { 
        this.name = name;
    }
    
    A.prototype = { 
        'getName': function () {
            return this.name;
        }
    }

    function B(name, age) {
        A.call(this, name); //继承父类属性
        this.age = age;
    }

    B.prototype = new A(); //继承父类方法
    B.prototype.constructor = B; //修复构造函数指向
    B.prototype.getAge = function () {
        return this.age;
    }
    var b = new B('B', 19);
    console.log(b.name); //B
    console.log(b.age); //19
    console.log(b.getName()); //B
    console.log(b.getAge()); //19
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值