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()

 

posted @ 2021-11-05 14:06  梨落清秀  阅读(20)  评论(0)    收藏  举报