首页 > Web开发 > 详细

JS——对象创建

时间:2017-11-17 15:46:20      阅读:223      评论:0      收藏:0      [点我收藏+]

1、原始创建

<script>
    person = new Object();//不要var
    person.firstname = "Bill";
    person.lastname = "Gates";
    person.age = 56;
    person.eyecolor = "blue";
    person.say = function () {
        console.log(person.firstname);
    }
    person.say();//Bill
</script>
<script>
    var person = {
        firstname: "John",
        lastname: "Doe",
        age: 50,
        eyecolor: "blue",
        say: function () {
            console.log(this.firstname);
        }
    };
    person.say();//John
</script>

2、进阶版本

<script>
    function CreatePserson(name) {
        var person = new Object();
        person.name = name;
        person.sayHi = function () {
            console.log(this.name);
        }
        return person;
    }
    var stu1 = CreatePserson("wu");
    stu1.sayHi();//wu
</script>

3、最终版本

<script>
    function Person(name, age) {
        this.name = name;
        this.age = age;
        this.say = function () {
            console.log(this.name + "===" + this.age);
        }
    }
    var per = new Person("wu",27);
    per.say();//wu===27
</script>

 

JS——对象创建

原文:http://www.cnblogs.com/wuqiuxue/p/7851447.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!