码迷,mamicode.com
首页 > 其他好文 > 详细

构造函数

时间:2019-01-05 22:54:06      阅读:228      评论:0      收藏:0      [点我收藏+]

标签:属性   创建对象   必须   lang   自己的   set   console   实例   代码   

<!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>

 

 

 

 

实例二:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>创建对象</title>

</head>
<body>
</body>
<script>

// 标准对象构造器
function Person(n, a, t){
// 局部变量可以理解成对象的私有属性
var secret = "秘密";
this.name = n;
this.age = a;
this.runType = t;
this.run = function(){
// 对象的方法可以访问(读取)自己的属性,但是尽量使用 this.xxxx 来访问
console.log(this.runType);
}
this.introduce = function (){
console.log("我是"+this.name+"我今年"+this.age+"岁了");
}
this.doSome = function(){
// 方法也可以 设置 自己的属性
this.runType = "??";
}
}

// new的过程实际上是在堆上为对象分配内存空间,然后再调用 构造器 的时候传入构造器中表示新建的对象,最后把 这个地址 也赋给 xiaoli 这个变量
// 本质上 所有对象变量 存储的都是一个 地址值,这个地址可以找到对象在堆上的内存,从而操作对象
var xiaoli = new Person("小丽", 20, "??");
console.log(xiaoli.name);
xiaoli.run();
xiaoli.introduce();

</script>
</html>

 

构造函数

标签:属性   创建对象   必须   lang   自己的   set   console   实例   代码   

原文地址:https://www.cnblogs.com/7qin/p/10226407.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!