每日学到 47 - JavaScript对象

创建对象

    1.基于Object的方式创建对象

	<script>
		var student = new Object();
		student.name = '张三';
		student.age = 22;
		student.javaScore = 98.5;
		student.print = function () {
			console.log('学生姓名:' + this.name + ",年龄:" + this.age + ",java分数:" + this.javaScore);
		}

		student.print();
	</script>

    2.对象字面量的方式创建对象

	<script>
		var student = {
			//属性:属性值
			name: '张三',
			age: 23,
			javaScore: 99.5,
			print: function () {
				console.log('学生姓名:' + this.name + ",年龄:" + this.age + ",java分数:" + this.javaScore);
			}
		}

		console.log(student.name);
		student.print();
	</script>

    3.工厂模式的方式创建对象

	<script>
		function createStudent(name, age, javaScore) {
			var student = new Object();
			student.name = name;
			student.age = age;
			student.javaScore = javaScore;
			student.print = function () {
				console.log('学生姓名:' + this.name + ",年龄:" + this.age + ",java分数:" + this.javaScore);
			}
			return student;
		}

		//创建对象
		var stu1 = createStudent("李四", 24, 99.5);
		console.log(stu1.name);
		console.log(stu1.age);
		console.log(stu1.javaScore);
		stu1.print();
		var stu2 = createStudent('王五', 19, 88.9);
		stu2.print();						
	</script>

    4.构造函数的方式创建对象

        构造函数一般以大写字母开头
        构造函数也是函数,只不过可以用来创建对象

	<script>
		function Student(name, age, javaScore) {
			this.name = name;
			this.age = age;
			this.javaScore = javaScore;
			this.print = function () {
				console.log('学生姓名:' + this.name + ",年龄:" + this.age + ",java分数:" + this.javaScore);
			}
		}

		var stu1 = new Student('如花', 18, 100);
		console.log(stu1.name);
		stu1.print();
	</script>

原型prototype

    每个函数都有一个prototype(原型)属性
    这个对象的用途是包含可以由特定类型的所有实例共享的属性和方法

	<script>
		function Student(name, age, javaScore) {
			this.name = name;
			this.age = age;
			this.javaScore = javaScore;
		}

		//在上面的构造函数中没有定义输出对象所有信息的函数,可以使用原型来进行添加
		Student.prototype.print = function () {
			console.log('学生姓名:' + this.name + ",年龄:" + this.age + ",java分数:" + this.javaScore);
		}

		var stu1 = new Student('翠花', 19, 99.9);
		console.log(stu1.name);
		stu1.print();
	</script>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值