1.直接给对象添加(对象通过字面量创建)
<!DOCTYPE html> <html> <body>
<p id="demo"></p>
<script> var person = { ? firstName: "Bill", ? lastName : "Gates", ? id ? ? : 678, }; person.name = function() { ? return this.firstName + " " + this.lastName; };
document.getElementById("demo").innerHTML = "My friend is " + person.name();? </script>
</body> </html>
2. 给对象实例添加(对象通过构造函数new一下创建)
无法为已有的对象构造器添加新属性
例如
Person.nationality = "English";
// Person 对象的构造器函数 function Person(first, last, age, eye) { ? this.firstName = first; ? this.lastName = last; ? this.age = age; ? this.eyeColor = eye; }
// 创建两个 Person 对象 var myFriend = new Person("Bill", "Gates", 62, "blue"); var myBrother = new Person("Steve", "Jobs", 56, "green");
// 向第一个对象添加 name 方法 myFriend.name = function() { ? return this.firstName + " " + this.lastName; };
// 显示全名 document.getElementById("demo").innerHTML = "My friend is " + myFriend.name();? </script>
3.给对象原型添加
所有 JavaScript 对象都从原型继承属性和方法
使用?prototype?属性
JavaScript prototype 属性允许您为对象构造器添加新属性:
function Person(first, last, age, eyecolor) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eyecolor;
}
Person.prototype.name = function() {
return this.firstName + " " + this.lastName;
};
给对象添加方法也类似?
|