JavaScript中给对象添加函数的方式

1.

function 类名(){

   this.属性;

}

var 对象名=new 类名();

function 函数名(){

  //执行代码

}

对象名.属性名=函数名;

对象名.属性名();

function Person(){

   this.name="abc";

   this.age=30;

}

function show1(){

   window.alert("hello"+this.name);

}

var p1=new Person();

p1.abc=show1;

p1.abc();

2.
 对象名.属性名=function(参数列表){

   //代码

}

//调用

对象名.属性名(实际参数);

function Person(){

  this.name="xx";

  this.age=20;

}

var p1=new Person();

p1.abc=function show1(){

  window.alert("hello"+this.name);

}

p1.abc();

3. 原型法(多个对象可共享函数)

 function Dog(){

}

var dog1=new Dog();

Dog.prototype.shout=function(){

  window.alert("dog");

}

dog1.shout();

var dog2=new Dog();

dog2.shout();

4. 使用传入的实参初始化属性

function Person(name,age){

   this.name=name;

   this.age=age;

}

this.show=function(){

   window.alert("hello"+this.name);

}

var p1=new Person("aa",21);

p1.show();

宝剑锋从磨砺出,梅花香自苦寒来。
原文地址:https://www.cnblogs.com/haimengqingyuan/p/5424998.html