之前定义JavaScript对象是这样定义的:let obj = {};
第一种创建语法:
创建JavaScript对象直接的实例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div>技能提升</div>
</body>
<script>
person = new Object();
person.firstname = "John";
person.lastname = "Doe";
person.age = 20;
person.eyecolor = "blue";
document.write(person);
console.log(person);
</script>
</html>
浏览器打印结果
第二种创建语法替代语法(使用对象:literals): person={firstname:"John",lastname:"Doe",age:20,eyecolor:''blue"} 打印结果:和上同,
第三种创建语法:使用对象构造器:如下例使用函数来构造对象--
function person(firstname,lastname,age,eyecolor){
this.firstname = firstname;
this.lastname = lastname;
this.age = age;
this.eyecolor = eyecolor;
}
myFather = new person("John","Doe","20","blue");
打印结果与上图同 注此时的对象名时myFather 而且对象构造器person是不能添加属性的,构造器能被不同对象重复使用
例:myFirst = new person("testFirst","testLast",30,"black"); mySecond = new person("faceFirst","faceLast",20,"gray");都是合法定义
错误示例:person.new = "new";此时要添加新属性应是myFather.new = "new"; 当然我们也可以在构造函数中添加新属性。
注:在JavaScript中,this通常指向的是我们正在执行的函数本身,或者是指向该函数所属的对象(运行时)
通过对象构造器向对象中添加函数
function person(firstname,lastname,age,eyecolor){
this.firstname = firstname;
this.lastname = lastname;
this.age = age;
this.changeName = changeName;
function changeName(name){
this.lastname = name;
}
}
myMother = new person("Jone","Doe",20,"green");
myMother.changeName("Doe");
function test(firstname,lastname,age,eyecolor){
this.firstname = firstname;
this.lastname = lastname;
this.age = age;
this.eyecolor = eyecolor;
this.changeName = changeName;
function changeName(name){
this.lastname = name;
}
}
myMother = new test("Jone","Doe",20,"green");
myMother.changeName("New Doe");
console.log("测试用例",myMother);