博主信息
博文 39
粉丝 0
评论 0
访问量 37391
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
JavaScript第一课:JS基本语法,对象创建的三种方法和区别 2018年9月11日 22:28
南通税企通马主任的博客
原创
794人浏览过

作业:创建对象的方式(字面量或构造函数)

实例

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>JS中的对象创建</title>
</head>
<body>
<h2>用字面量创建对象</h2>
<hr>
<script >
let obj = 100;
let obj1 = '南通税企通';
document.write(obj1,'<br>',obj,'<hr>');

let obj2 = {
    name:'arthur',
    position:'管理员',
    salary:19800,
    secret: function () {
        return this.salary;
    }
};
document.write(obj2.name,'<br>');
document.write(obj2.position,'<br>');
document.write(obj2.secret(),'<hr>');
</script>

<h2>用构造函数创建对象</h2>
<hr>
<script>
    function Staff(name,position,salary){
        this.name = name;
        this.position = position;
        this.salary = salary;
        this.getName = function () {
            return [this.name,this.position,this.salary];
        }
    }
    let staff1 = new Staff('arthur','admin',19800);
    let staff2 = new Staff('kitty','assistant',8800);
    document.write(staff1.getName(),'<br>');
    document.write(staff2.getName(),'<hr>');

    document.write(typeof staff1.constructor,'<br>');
    document.write(staff1.constructor,'<br>');
    document.write(staff1.constructor === Staff,'<br>');
    document.write(staff1 instanceof Staff,'<br>');
    document.write(staff1 instanceof Object,'<hr>');

    document.write(this,'<br>');
    Staff('baby','desktop','3800');
    document.write(window.getName(),'<hr>');

    staff3 = new Staff();
    Staff.call(staff3,'a','a1','123');
    document.write(staff3.getName(),'<br>');
    Staff.apply(staff3,['b','b2',321]);
    document.write(staff3.getName(),'<hr>');
</script>

<h2>原型模式创建对象</h2>
<hr>
<script >
    function Shop(shoes,clothes,jeans) {
        Shop.prototype.shoes = shoes;
        Shop.prototype.clothes = clothes;
        Shop.prototype.jeans = jeans;
        Shop.prototype.getInfo = function () {
            return this.shoes +',' +this.clothes +','+ this.jeans;
        }
    }
    let shop1 = new Shop('李宁','班尼路','某易斯.威登');
    document.write(shop1.getInfo(),'<br>');
    let shop2 = new Shop('乔丹','李维斯','某思哲');
    document.write(shop1.getInfo(),'<br>');
    document.write(shop2.getInfo(),'<hr>');

    document.write(Shop.constructor,'<br>');
    document.write(typeof Shop.prototype,'<br>');
    document.write(Shop.prototype.constructor,'<hr>');

    document.write(Shop.constructor === shop1.constructor.prototype.constructor);

</script>
</body>
</html>

运行实例 »

点击 "运行实例" 按钮查看在线实例

总结:写完了,终于把JS中对象了解到一定程度了,所谓的一切皆对象,就说明了一切皆虚幻,存在于自己怎么理解而已!


批改状态:合格

老师批语:
本博文版权归博主所有,转载请注明地址!如有侵权、违法,请联系admin@php.cn举报处理!
全部评论 文明上网理性发言,请遵守新闻评论服务协议
0条评论
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号

  • 登录PHP中文网,和优秀的人一起学习!
    全站2000+教程免费学