方式一:定义对象时,直接添加属性和方法
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