对象:指某个事物具有的属性和方法。在javaScript中创建对象的方法一共有三种:字面量方式,调用系统的构造函数,自定义构造函数。
1.字面量方法,字面量最通俗的解释就是一眼就能知道值的量。比如var x = ‘aaaa’,就是把字面量'aaaa'赋值给了变量x.
<script>
var person = {
name:"小明",
age:18,
address:"武汉",
eat:function(){
console.log("饺子");
}
}
person.name;
person.eat();
</script>
2.调用系统的构造函数
<script>
var person = new Object();
person.name = "小明";
person.age = 18;
person.eat = function(){
console.log("饺子");
}
alert(person.name);
person.eat();
</script>
3.自定义构造函数
<script>
function Person(name,age){
this.name = name;
this.age = age;
this.eat = function(){
console.log("饺子");
}
}
var per = new Person("小明",18);
alert(per.name);
per.eat();
</script>
4.也可以通过工厂模式进行创建
<script>
function createObject(name,age){
var obj = new Object();
obj.name = name;
obj.age = age;
obj.eat = function(){
console.log("饺子");
}
return obj;
}
var person = createObject("小明",18);
alert(person.name);
</script>
5.通过原型给构造函数添加方法
<script>
function Person(name,age){
this.name = name;
this.age = age;
}
Person.prototype.eat = function(){
alert("饺子");
}
var person = new Person();
person.eat();
</script>