向javascript对象添加方法比向对象构造函数添加方法要容易。我们需要将方法分配给现有属性以确保任务完成。
在下面的示例中,首先创建对象类型,然后再创建对象的属性。创建完属性后,将为每个对象分配一个方法,并根据需要使用该方法访问属性。
<html> <body> <p id = "prop"></p> <script> function Business(name, property, age, designation) { this.Name = name; this.prop = property; this.age = age; this.designation = designation; } var person1 = new Business("Trump", "$28.05billion", "73", "President"); var person2 = new Business("Jackma", "$35.6 billion", "54", "entrepeneur"); person1.det = function() { return this.Name + " "+" 拥有净资产 "+ "" + this.prop; }; person2.det = function() { return this.Name + " "+" 拥有净资产 "+ "" + this.prop; }; document.write(person2.det() +" and "+person1.det()); </script> </body> </html>
Jackma 拥有净资产 $35.6 billion and Trump 拥有净资产 $28.05billion