JavaScript-04-JS产生对象以及批量产生对象
Posted 淡然微笑
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JavaScript-04-JS产生对象以及批量产生对象相关的知识,希望对你有一定的参考价值。
1.1创建对象
<script text="text/javascript"> //1.创建对象 //this this 所在的函数属于哪个对象,this就代表这个对象 //1.1直接创建 var dog = { name: ‘San‘, age: 18, height: 1.55, dogFriends: [‘Bob‘,‘Lili‘], eat:function (someThing) { console.log( this.name +‘吃‘ + someThing); }, run:function (someWhere) { console.log(this.name +‘跑‘ + someWhere); } };//object console.log(typeof dog); //1.2输出这只狗对象的属性和行为 console.log(dog.age,dog.dogFriends); dog.eat(‘肉‘); dog.run(‘健身房‘); </script>
2.通过构造函数批量产生对象
<script type="text/javascript"> //通过构造函数批量产生对象 //普通函数->构造函数 var Dog = function () { console.log(‘这是一个普通函数‘); }; //普通调用 Dog(); // alloc init -> new var dog1 = new Dog(); var dog2 = new Dog(); console.log(dog1,dog2); </script>
3.验证批量产生对象
<script type="text/javascript"> //创建构造函数 -> 抽象 var Dog = function () { this.name = null; this.age = null; this.dogFriends = []; this.height = null; this.eat = function (someThing) { console.log(this.name + ‘吃‘ + someThing); } this.run = function (someWhere) { console.log(this.name + ‘跑‘ + someWhere); } } //批量产生对象 var dog1 = new Dog(); dog1.name = ‘Peter‘; dog1.age = 15; dog1.dogFriends = [‘A‘,‘B‘]; var dog2 = new Dog(); dog2.name = ‘Bob‘; dog2.age = 18; dog2.dogFriends = [‘C‘,‘D‘]; console.log(dog1,dog2); //创建构造函数 -> 抽象 var Dog1 = function (name,age,dogFriends,height) { this.name = name; this.age = age; this.dogFriends = dogFriends; this.height = height; this.eat = function (someThing) { console.log(this.name + ‘吃‘ + someThing); } this.run = function (someWhere) { console.log(this.name + ‘跑‘ + someWhere); } } var dog3 = new Dog1(‘Peter‘,15,[‘A‘,‘B‘],1); console.log(dog3); </script>
以上是关于JavaScript-04-JS产生对象以及批量产生对象的主要内容,如果未能解决你的问题,请参考以下文章