给JS对象添加属性和方法

2022-08-20 12:48:59

方式一:定义对象时,直接添加属性和方法

functionPerson(name,age,sex){this.name= name;this.age= age;this.sex= sex;this.code=function(){
                console.log(this.name+"is coding");}}var xiaoming=newPerson("xiaoming",10,"man");
        console.log(xiaoming);// {name: "xiaoming", age: 10, sex: "man", code: ƒ}
        xiaoming.code();// xiaoming is coding

方式二:通过"对象.属性名"添加

functionFruit(){}var tomato=newFruit();
        tomato.name="xihongshi";
        tomato.color="red";
        tomato.use=function(){
            console.log(this.name+"can be to eat");}
        console.log(tomato);
        tomato.use();

方式三:通过 prototype (原型)添加

functionAnimal(){};
        Animal.prototype.foots=4;
        Animal.prototype.weight=200;
        Animal.prototype.hobby="sing";
        Animal.prototype.have=function(){
            console.log("the animal have "+this.foots+" foot");}var pig=newAnimal();
        console.log(pig);
        pig.have();// the animal have 4 foot
  • 作者:蓝色清晨_
  • 原文链接:https://blog.csdn.net/yingleiming/article/details/114359622
    更新时间:2022-08-20 12:48:59