js向对象添加属性

  • Post author:
  • Post category:其他


1、使用 对象.属性名 添加

<script>
    function func(){
        console.log(this.name);
    }
    var obj = {};
    obj.name = "star";
    obj.sayHello = func;
    obj.sayHello(); //star
</script>

2、使用 对象[属性名]添加

<script>
    var obj = {};
    obj['age'] = 25;
    var age = 'age';
    console.log(obj.age, obj['age'], obj[age]); //25 25 25
</script>

3、使用 prototype添加

<script>
    var star = Person();
    console.log(star); //undefined
    star = new Person();
    console.log(star, star instanceof Person); //Person true 
    star.name = "moon";
    Person.prototype.sayHi = function(){
        console.log(this.name); 
    }
    star.sayHi(); //moon
</script>



版权声明:本文为weixin_43275277原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。