js面向对象,7种创建方式

	window.onload = function(){   //字面量方式创建
			var obj = {
				name:'如花',
				age:22,
				run:function(){
					alert(this.name);
				}
			}
			console.log(obj.name,obj.age);
			obj.run();
		};
		
		//实列创建
		var box = new Object();
		box.name = 'ujiuye';
		box.age = 18;
		box.run = function(){
			console.log(this.name);
			return this.name  +  this.age;
		}
		console.log(box.run());
		
		//工厂模式创建对象
		function createObject(name,age){
			var obj = new Object();
			obj.name = name;
			obj.age = age;
			obj.run = function(){
				return this.name + this.age;
			}
			return obj;
		}
		var box1 = createObject('Lee',100);
		var box2 = createObject('jack',200);
		alert(box1.run());
		alert(box2.run());
		
		//构造函数创建对象
		function Ou(name){
			this.name = name;
			this.eat = function(){
				console.log('吃饭了');
			}
		}
		var s1 = new Ou('mm');
		var s2 = new Ou('qiqi');
		console.log(s1 instanceof Ou);
		console.log(s1.eat == s2.eat);
		
		//原型创建对象
			function Str(){};
			Str.prototype.name = '小明';
			Str.prototype.sex = 'male';
			Str.prototype.run = function(){
				console.log('我是一个函数');
			}
		var obj = new Str();
		console.log(obj.name);	
		var  obj1 = new Str();
		console.log(obj.name);
		console.log(obj.run == obj1.run);
		混合模式创建(构造+原型)
		window.onload = function () {
    //混合模式  构造函数+原型
    //构造函数写可变的属性和变量
    function  Student(name) {
        this.name = name;
        this.eat = 18;
    }
    //破坏了封装性
    Student.prototype.eat = function () {
        console.log("吃饭");
    };
    //实例对象
    var s1 = new Student("小明");
    var s2 = new Student("如花");
    console.log(s1.name,s2.name); //小明 如花
    console.log(s1.eat == s2.eat); //true;
}

动态混合模式
window.onload = function () {
    //混合模式  构造函数+原型
    //构造函数写可变的属性和变量
    function Student(name) {
        this.name = name;
        this.eat = 18;
        /*Student.prototype.eat = function () {
         console.log("吃饭");
         } 调试还是每创建一个对象就会执行一次,原型是只初始化一次的*/
        //判断是否存在,不存在则添加
        if (!(typeof this.eat == "function")) {
            Student.prototype.eat = function () {
                console.log("吃饭");
            }
        }
        //实例对象
         var s1 = new Student("小明");
        var s2 = new Student("如花");
        console.log(s1.name, s2.name); //小明 如花
        console.log(s1.eat == s2.eat); //true;
    }
}    
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值