【JavaScript 6连载】三、构造函数
<!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 = "
最新文章
- sp_MSforeachtable 与 sp_MSforeachdb
- Base64正反编码
- 邻接矩阵有向图(三)之 Java详解
- 菜鸟教程之工具使用(十四)——Maven项目右击没有“Maven”菜单选项
- 【WPF】Winform调用WPF窗体注意事项
- Java中数组的特性
- lof基金
- 快速排序算法-C语言实现
- iOS利用单例实现不同界面间的数据传输
- The only legal comparisons are between two numbers, two strings, or two dates.
- Eclipse C/C++环境配置
- 升级10.11后使用CocoaPod出现-bash: pod: command not found 解决办法-备
- CSA 第五届研讨会 想象
- JavaScript一个鼠标滚动事件的实例
- 终于将SAP系统完全配置通过了
- macos 安装sublime text 3,如何安装插件
- base编码解码
- 可遇不可求的Question之flash的socket连接安全策略文件篇
- 用Canvas做视频拼图
- Windows下的PHP 5.3.x安装 Zend Guard Loader
热门文章
- 检测到目标URL存在http host头攻击漏洞
- python-面向对象-03_面向对象基础语法
- laravel项目出现Non-static method Redis::hGet() cannot be called statically的解决方法
- MySQL安装失败解决的方法
- 我的Chrome插件
- [LeetCode] 619. Biggest Single Number_Easy tag: SQL
- AC自动机模板2
- MySQL数据类型--与MySQL零距离接触2-8查看数据表
- [pat]1007 Maximum Subsequence Sum
- Graphviz