zoukankan      html  css  js  c++  java
  • JS中创建自定义对象的方法

    1.直接给对象扩充属性和方法;

    2.对象字面量;

    3.工厂方式;

    4.构造函数方式;

    5.原型方式;

    6.混合方式。

    <script>
    		// 1.直接给对象扩充属性和方法;
    		var cat = {};
    		cat.name = '小白';
    		cat.color = 'blue';
    		cat.food = 'fish';
    		cat.skill = function () {
    			alert('喵喵~~~');
    		}
    		cat.skill();
    		//2.对象字面量
    		var cat2 = {
    			name: '小白',
    			color: 'blue',
    			food: 'fish',
    			skill: function () {
    				alert('喵喵~~~');
    			}
    		};
    		console.log(cat2.name);
    		//3.工厂方式
    		function cat4(n, c) {
    			var cat = {};
    			cat.name = n;
    			cat.color = c;
    			cat.food = 'fish';
    			cat.skill = function () {
    				alert('喵喵~~~');
    			}
    			return cat;
    		} 
    		var cat5 = cat4('小白','red');
    		console.log(cat5.name);
    		console.log(cat5.color);
    		//4.构造函数方式
    		function Cat6(n,c) {
    			this.name = n;
    			this.color = c;
    			this.food = 'fish';
    			this.skill = function () {
    				alert('喵喵');
    			}
    		}
    		var cat7 = new Cat6('小黄','yellow');
    		console.log(cat7.name);
    		console.log(cat7.color);
    		//5.原型方式
    		function Cat8() {};
    		Cat8.prototype.name = '小白';
    		Cat8.prototype.color = 'white';
    		Cat8.prototype.food = 'fish';
    		Cat8.prototype.skill = function () {
    			alert('喵喵~~~');
    		}
    		var cat9 = new Cat8();
    		console.log(cat9.food);
    		//6.构造函数混合方式
    		function Cat(n, c) {
    			this.name = n;
    			this.color = c;
    			this.food = 'fish';
    		}
    		Cat.prototype.skill = function () {
    			alert('喵喵hahah~~~');
    		}
    		var cat10 = new Cat('红','red');
    		console.log(cat10.name);
    		cat10.skill();
    	</script>
    

      

  • 相关阅读:
    弹窗多内容,灵活布局计算方式总结
    暖场广告设计方案
    UIStackView上手教程
    多弹窗排序总结
    常用的code snipper
    iOS开发常用技能点(持续更新中。。。)
    32位和64位系统区别及int字节数
    liunx环境,摄像头无法识别,解决方案
    TCP/IP 笔记 7 Ping
    TCP/IP 笔记 6 netstat -s 命令查看每个协议统计数据
  • 原文地址:https://www.cnblogs.com/handsomehan/p/5882119.html
Copyright © 2011-2022 走看看