zoukankan      html  css  js  c++  java
  • Effective JavaScript Item 39 绝不要重用父类型中的属性名

    本系列作为Effective JavaScript的读书笔记。

     

    假设须要向Item 38中的Actor对象加入一个ID信息:


    function Actor(scene, x, y) {
    	this.scene = scene;
    	this.x = x;
    	this.y = y;
    	this.id = ++Actor.nextID;
    	scene.register(this);
    }
    Actor.nextID = 0;
    

    同一时候。也须要向Actor的子类型Alien中加入ID信息:


    function Alien(scene, x, y, direction, speed, strength) {
    	Actor.call(this, scene, x, y);
    	this.direction = direction;
    	this.speed = speed;
    	this.strength = strength;
    	this.damage = 0;
    	this.id = ++Alien.nextID; // conflicts with actor id!
    }
    Alien.nextID = 0;
    

    Alien的构造函数中,也对id属性进行了赋值。因此。在Alien类型的实例中,id属性永远都是通过Alien.nextID进行赋值的。而不是Actor.nextID

    父类型的id属性被子类型的id属性覆盖了。

     

    解决方式也非常easy,在不同的类型中使用不同的属性名:


    function Actor(scene, x, y) {
    	this.scene = scene;
    	this.x = x;
    	this.y = y;
    	this.actorID = ++Actor.nextID; // distinct from alienID
    	scene.register(this);
    }
    Actor.nextID = 0;
    function Alien(scene, x, y, direction, speed, strength) {
    	Actor.call(this, scene, x, y);
    	this.direction = direction;
    	this.speed = speed;
    	this.strength = strength;
    	this.damage = 0;
    	this.alienID = ++Alien.nextID; // distinct from actorID
    }
    Alien.nextID = 0;
    

    总结

    1. 注意全部父类型中使用的属性名称不要和子类型中的反复。
    2. 在子类型中不要重用父类型中已经使用的属性名。


  • 相关阅读:
    centons 7 清机 脚本
    LNMP 一键安装脚本
    mysql 命令
    docker 命令笔记
    zabbix agent 编译安装
    zabbix 用Telegram报警!!!
    如果你也用过 struts2.简单介绍下 springMVC 和 struts2 的区别有哪些
    @RequestMapping 注解用在类上面有什么作用
    什么是 MyBatis
    Mybatis 动态 sql 是做什么的?都有哪些动态 sql?能简述一下动态 sql 的执行原理不
  • 原文地址:https://www.cnblogs.com/wzzkaifa/p/7160407.html
Copyright © 2011-2022 走看看