11.4创建对象 js
//字变量 json
//常用于数据解析
var student={
id:10001,
name="张三"
scores: [
{subject:"html",score: 90 },
{subject:"js",score: 90 }
]
}
// function
//推荐 常用方式
function student(id, name) {
this.id = id;
this.name = name
this.scores = [
{subject: "html", score: 90},
{subject: "js", score: 90}
]
}
//扩展
student.prototype.sex="男"
student.prototype.eat = function (food) {
console.log("吃" + food)
}
var stu = new student(1000,"张三");
stu.eat("米饭");
console.log(stu.sex)
// object
// 缺点:代码重复率高
//好处:可以随机扩展
var stu2 = new Object();
stu2.id = 1000;
stu2.name = "张三";
stu2.scores = [
{subject: "html", score: 90},
{subject: "js", score: 90}
]
function student(id, name) {
this.id = id;
this.name = name
this.eat = function (food) {
console.log("吃" + food)
return this
},
this.sleep = function(){
console.log("睡")
return this
}
}
var stu = new student(1001,"张三");
//方法一
// stu.eat("苦瓜");
// stu.sleep();
//链式编程
//方法二
stu.eat("苦瓜").sleep().eat("苦瓜").sleep().eat("苦瓜").sleep().eat("苦瓜").sleep().eat("苦瓜").sleep()
浙公网安备 33010602011771号