Blogger Information
Blog 7
fans 0
comment 0
visits 4546
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
7月10日作业:1、写一个构造函数来创建对象 2、向构造函数的prototype 中添加成员,实现数据在实例间共享
陈康民的博客
Original
627 people have browsed it

1、写一个构造函数来创建对象


实例

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<!--1、写一个构造函数来创建对象-->
<script>
    //构造函数
var CreateObj=function(){
    this.name1='小明';
    this.name2='小红';
    this.get=function(value){
        var job='程序员';
        return value+'是'+job;
    };
};
//创建构造函数实例 test1
var test1=new CreateObj();
document.write(test1.get(test1.name1));
//创建构造函数实例 test2
var test2=new CreateObj();
document.write(test2.get(test2.name2))
</script>


</body>
</html>

运行实例 »

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

2、向构造函数的prototype 中添加成员,实现数据在实例间共享

实例

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<!--2、向构造函数的prototype 中添加成员,实现数据在实例间共享-->

<script>
    //构造函数,添加原型属性 prototype

    //建立空对象封装全局成员CreateObj2,CreateObj3
    var yuangong={};
    //构造函数,CreateObj2
    yuangong.CreateObj2=function(){
        this.name3='3号员工';
        this.name4='4号员工';

    };
    //构造函数,CreateObj3
    yuangong.CreateObj3=function(){
        this.name5='5号员工';
        this.name6='6号员工';
    };

    //创建一个共用的带有原型属性prototype的函数
    yuangong.jobName=function(){};
    yuangong.jobName.prototype.get=function(value){
        var job='搬砖工';
        return value+'是'+job
    };

    //get功能被多处调用
    var diaoyong1 = new yuangong.jobName;
    var diaoyong2 = new yuangong.jobName;

    //输出结果
    document.write(diaoyong1.get(new yuangong.CreateObj2().name4));
    document.write(diaoyong2.get(new yuangong.CreateObj3().name5));
</script>




</body>

运行实例 »

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


Correction status:qualified

Teacher's comments:记住函数的原型属性的值,还是一个对象, 这个很关键
Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!