js中对象的创建

来源:互联网 发布:网络互动直播新闻 编辑:程序博客网 时间:2024/06/07 00:23

在js中有两种创建对象的方法,一种是直接创建,一种是像其他的语言一样,通过调用构造函数的方式批量的创建对象

先看第一种方法,我们通过页内的js来实现这个功能

<html lang="en"><head>    <meta charset="UTF-8">    <title>js中创建对象</title>    <script type="text/javascript">//        创建一个狗的对象       var dog = {           name:'afa',           age :18,           height:1.55,           dogfriend:['Lili','duanchao'],            eat:function () {                console.log('吃')            },           run:function () {               console.log('跑')           }       };       console.log(dog.eat);    </script></head><body></body></html>

接着我们来看一下,通过构造函数,与其他的语言,构造函数是一个批量的创建对象的,通常来讲我们都是先定义一个类,通过调用类的构造方法,来创建对象,如oc中的alloc,java.中new;

<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <title>创建构造函数</title>    <script>        //创建构造函数        var Dog = function () {            this .name = null;            this .age = null;            this .dogfriend = [];            this.eat = function () {//                console.log(this.name+'吃'+something);            };            this.run = function () {//                console.log(this.name+'跑'+somewhere);            }        };        var dog1 = new Dog();        var dog2 = new Dog();        dog1.name = '阿里';        dog1.age = 12;        dog1.dogfriend = ['阿花'];        dog2.name = '阿华';        dog2.age = 12;        dog2.dogfriend = ['阿花'];        console.log(dog1.name);        console.log(dog2.name);    </script></head><body></body></html>

我们将构造函数,稍微演进一下,也就是当我初始化对象,传入参数,完成参数的赋值

var Dog = function () {        this .name = null;        this .age = null;        this .dogfriend = [];        this.eat = function () {

// console.log(this.name+’吃’+something);
};
this.run = function () {
// console.log(this.name+’跑’+somewhere);

        }  };    var dog3 = new Dog1('阿龙',12,['dog','digj','djgk']);
0 0
原创粉丝点击