首页 > 其他 > 详细

构造函数

时间:2016-11-22 09:32:03      阅读:181      评论:0      收藏:0      [点我收藏+]

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>03-构造函数</title>
<script>
// 构造函数就是一种专门用来创建对象的一种函数


// 使用系统原生的构造函数创建对象
// var student =new Object();
// student.name = ‘张三‘;
// student.sex = ‘b‘;
// student.study = function(){
// console.log(‘学习‘);
// }
// student.study();

// 自定义构造函数
var name = ‘张三‘;
console.log(name);

function Student(){
this.name = "李四";
this.age = 18;
this.sex = ‘b‘;
this.play = function(){
console.log(‘谁晚上跟‘ + this.name + ‘一起LOL‘);
}
}

// var st1 = new Student();
// st1.play();
// console.log(st1.name);


// var st2 = Student();
// // st2.play();
// // console.log(st2.name);
// console.log(window.name);
// console.log(name);
// console.log(age);


// 自定义构造函数需要注意:1、构造函数首字母大写,为了跟普通的函数区分,2、在使用的时候,必须使用new关键字,3、返回值就是当前对象本身

// 调用构造函数的步骤:
/*
1、创建一个新对象
2、将构造函数的作用域赋给这个新对象
3、执行构造函数的代码
4、返回新对象
*/

// 使用构造函数的时候,必须使用new关键字,如果不使用new,会造成,对象无法返回,并且会影响函数调用者的环境变量

function Student1(){
this.name = "李四";
this.age = 18;
this.sex = ‘b‘;
this.play = function(){
console.log(‘谁晚上跟‘ + this.name + ‘一起LOL‘);
}
}


// 使用instanceof来判断某个对象是否属于某个构造函数类型
var st3 = new Student1();
console.log(st3 instanceof Student1);
console.log(st3 instanceof Object);

 

</script>
</head>
<body>

</body>
</html>

构造函数

原文:http://www.cnblogs.com/qh926/p/6087818.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!