向JavaScript对象构造函数添加方法?
向对象构造函数 添加方法不同于向 普通对象添加方法。我们不能像普通对象那样添加方法。要在对象构造函数中创建方法,必须将其添加到对象构造函数中。
示例
在下面的示例中,该方法 被添加到构造函数中,因此,我们获得了合法的值。
<html> <body> <script> function Business(name, property, age, designation) { this.Name = name; this.prop = property; this.age = age; this.designation = designation; this.name = function() { return this.Name }; } var person1 = new Business("Trump", "$28.05billion", "73", "President"); document.write(person1.name()); </script> </body> </html>
输出结果
Trump