美文网首页
给对象添加属性

给对象添加属性

作者: 王家薪 | 来源:发表于2018-06-05 11:49 被阅读13次

    方法1 :

    let objc = {}; // objc必须初始化
    objc.name = '王五花'
    

    方法2 :

    let objc = {
        age:10,
    }
    
    objc = {
        ...objc, // 遍历objc的所有属性
        name: '王五花',
    }
    
    // objc = {age:10,name:'王五花'}
    

    扩展阅读

    由于没有js的底子 学习RN遇到很多无法理解的问题
    比如下面的这个代码

    export default class Regist extends Component {
        constructor() {
            super();
            this.props.name = "王五花";
        }
    
        render() {
            
            return(
                <View style = {styles.view}/>
            );
        }
    };
    

    报错:
    Unhandled JS Exception: TypeError: Cannot set property 'name' of undefined
    最初对这个错误提示有一个错误的理解, 以为是因为 props 中没有 name 这个属性造成的, 所以我有了一个错误的解决方案:

    export default class Regist extends Component {
        constructor() {
            super();
            this.props = {'name':'王五花'};
        }
    
        render() {
            
            return(
                <View style = {styles.view}/>
            );
        }
    };
    

    这样运行不报错了, 虽然看起来没有问题, 但是这么做相当于给 props 重新赋值了, 而不是增加一个 name 属性, 这样的后果就是父类的 props 属性被完全舍弃了.

    事实上 this.props.name = "王五花"; 这句代码是没有问题的.

    那为什么造成这个错误呢? 是因为 props 没有初始化, undefined 的不是 name 而是 props!

    正确的做法

    export default class Regist extends Component {
        // 之前以为初始化的时候 props 可以写也可以不写, 知道遇到这样的错误才理解为什么这样写, super 会初始化 props
        constructor(props) { 
            super(props);
            this.props.name = "王五花";
        }
    
        render() {
            
            return(
                <View style = {styles.view}/>
            );
        }
    };
    

    相关文章

      网友评论

          本文标题:给对象添加属性

          本文链接:https://www.haomeiwen.com/subject/gqepsftx.html