JS JavaScript对象

之前定义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);

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值