前端学习:JS(面向对象)代码笔记

前端学习:JS面向对象知识学习(图解)

创建类和对象

创建对象方式1调用Object函数

<body>
</body>
<script type="text/javascript"> //新建英雄:刘备
var hero=new Object();
hero.name='刘备';
hero.blood=100;
hero.weapon='双股剑';
hero.attack=function(){
return this.name+'使用'+this.weapon+'发起了攻击';
}; alert(hero.attack()); var hero2=new Object();
hero2.name='关羽';
hero2.blood=100;
hero2.weapon='青龙偃月刀';
hero2.attack=function(){
return this.name+'使用'+this.weapon+'发起了攻击';
}; alert(hero2.attack()); </script>

创建对象方式2使用字面形式

<body>
</body>
<script type="text/javascript"> var stu1={
name:'张三',
age:28,
sex:'男',
show: function(){
return '我的名字是:'+this.name+'\n我的性别是:'+this.sex+'\n我的年龄是:'+this.age;
}
}; alert( stu1.show() ); var stu2={
name:'李四',
age:18,
sex:'女',
show: function(){
return '我的名字是:'+this.name+'\n我的性别是:'+this.sex+'\n我的年龄是:'+this.age;
}
}; alert( stu2.show() ); </script>

创建对象方式3使用工厂函数创建多个对象

<body>
</body>
<script type="text/javascript"> //形参
var createPerson=function(name,age,sex){
var person = new Object();
person.name=name;
person.age=age;
person.sex=sex;
person.show=function(){
return '我的名字是:'+this.name+'\n我的性别是:'+this.sex+'\n我的年龄是:'+this.age;
}
return person;
}; var p1=createPerson('张三',18,'男');
var p2=createPerson('李四',19,'男');
var p3=createPerson('王五',20,'男'); alert(p1.show());
alert(p2.show());
alert(p3.show()); </script>

创建对象方式4调用构造函数创建对象

<body>
</body>
<script type="text/javascript"> //定义一个Person类
function Person(name,age,sex){
//this代表的是当前对象 //当前对象的名字=需要设置的名字
this.name=name;
this.age=age;
this.sex=sex; this.show=function(){
return '我的名字是:'+this.name+'\n我的性别是:'+this.sex+'\n我的年龄是:'+this.age;
} } //创建三个对象
var p1=new Person('张三',27,'男');
var p2=new Person('李四',28,'男');
var p3=new Person('王五',29,'男'); alert(p1.show());
alert(p2.show());
alert(p3.show()); console.log(p1.show===p2.show);
console.log(p1.show===p3.show); </script>

静态成员和实例成员

静态成员和实例成员

<body>
</body>
<script type="text/javascript"> //静态成员 类名.成员名
/*
var MyMath={
PI:3.1415,
MAX:function(){
return 9999;
},
MIN:function(){
return 1;
}
}; console.log(MyMath.PI);
console.log(MyMath.MAX());
console.log(MyMath.MIN());
*/
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ //实例成员 对象名.成员名
function Student(name,age,sex){ this.name=name;
this.age=age;
this.sex=sex; this.show=function(){
return 'name='+name+'\nage='+age+'\nsex='+sex;
}
} //通过Student类的构造函数创建一个具体的实例对象
var stu1=new Student('小红帽',18,'女');
var stu2=new Student('大灰狼',28,'男'); console.log('姓名:'+stu1.name );
console.log('姓名:'+stu2.show() ); </script>

原型

使用全局函数

<body>

</body>
<script type="text/javascript"> function Student(name,age,sex){ this.name=name;
this.age=age;
this.sex=sex;
this.show=show; }
//全局函数
var show=function(){
return 'name='+name+'\nage='+age+'\nsex='+sex;
}; var stu1=new Student("DICK",22,"男");
var stu2=new Student("DICK",22,"男"); //比较的是这两个对象中show方法保存的内存地址
console.log(stu1.show===stu2.show); //true </script>

使用构造函数的原型解决方法的重复创建问题

<body>

</body>
<script type="text/javascript"> //得到一个结论:以后我们在定义一个类的函数的时候,不要定义在该类的构造函数中,应该
//定在该类的构造函数的原型中,这样更加高效一些. //Student类的构造函数
function Student(name,age,sex){ this.name=name;
this.age=age;
this.sex=sex; } //向Student类的构造函数的原型中插入show方法
Student.prototype.show=function(){
return '在原型中生成的: name='+this.name+'\nage='+this.age+'\nsex='+this.sex;
}; var stu1=new Student("DICK",22,"男");
var stu2=new Student("KING",22,"男"); console.log(stu1.show());
console.log(stu2.show()); //比较的是这两个对象中show方法保存的内存地址
console.log(stu1.show===stu2.show); //true </script>

对象的原型

<body>
</body>
<script type="text/javascript"> //Student类的构造函数
function Student(name,age,sex){ this.name=name;
this.age=age;
this.sex=sex;
this.eat=function(){
console.log('我在构造函数中吃东西');
} } Student.prototype.eat=function(){
console.log('我在构造函数的原型中吃东西');
} //构造方法的原型 Student.prototype
//对象的原型 对象名.__proto__
var stu=new Student("KING",22,"男"); //我们发现构造方法的原型和对象的原型指向的是同一个地址
//console.log(stu.__proto__===Student.prototype); //当构造函数中和构造函数的原型中同时定义了同一个方法,这个时候会调用构造函数中的eat方法.
stu.eat(); </script>

属性的查找规则

<body>
</body>
<script type="text/javascript">
//Student类的构造函数
function Student(name,age,sex){ this.name=name;
this.age=age;
this.sex=sex; } //在Student类的构造函数的原型中存入属性
Student.prototype.txt='xxx'; var stu1=new Student("KING",22,"男");
//该段代码并没有修改掉原型中txt的值,是在在stu1对象中新建了一个txt属性=abc
//stu1.txt='abc';
Student.prototype.txt='ABC';
var stu2=new Student("KING",22,"男"); console.log('stu1='+stu1.txt); //abc
console.log('stu2='+stu2.txt); //xxx </script>

在原型中写入多个方法属性-精简写法

<body>
</body>
<script type="text/javascript"> /*
function Person(){ }
Person.prototype.eat=function(){
console.log('eat');
} Person.prototype.run=function(){
console.log('run');
} Person.prototype.sleep=function(){
console.log('sleep');
} Person.prototype.from='地球 '; var p1=new Person();
p1.eat();
p1.run();
p1.sleep();
*/ function Person(){ }
Person.prototype={
from: '地球',
eat: function(){
console.log('eat');
},
run: function(){
console.log('run');
},
sleep: function(){
console.log('sleep');
}
}; var p1=new Person();
p1.eat();
p1.run();
p1.sleep();
alert(p1.from); </script>

原生对象的原型

<body>
</body>
<script type="text/javascript">
//Array类的对象
var arr=[]; console.log(Array.prototype===Array.prototype); //true
// 对象的原型 构造函数的原型
console.log(arr.__proto__===Array.prototype); //true console.log(Object.prototype===Array.prototype); //false </script>

拓展原生对象中原型的方法

<body>
</body>
<script type="text/javascript">
var arr=[21,22,43,67,12,34,20,10];
console.log('排序前: '+arr);
arr.sort();
console.log('排序后: '+arr); //求出数组中所有的偶数的和
//拓展Array类构造函数的原型中的方法: getSum() Array.prototype.getSum=function(){
var sum=0;
for(var i=0;i<this.length;i++){
if(this[i]%2==0){
sum+=this[i];
}
}
return sum;
} //错误的写法!!!!!!
/*
Array.prototype={
getSum:function(){
var sum=0;
for(var i=0;i<this.length;i++){
if(this[i]%2==0){
sum+=this[i];
}
}
return sum;
}
};
*/ console.log(arr.getSum()); </script>

案例:随机生成方块

案例前的练习

Demo01(JS插入与使用)

<body>

</body>
<script type="text/javascript" src="index1.js"></script>
<script type="text/javascript" src="index2.js"></script>
<script type="text/javascript" src="index3.js"></script>
<script type="text/javascript"> console.log(num1);
console.log(num2);
console.log(num3);
fn1();
fn2();
fn3();
</script>

index1.js

var num1=111;

function fn1(){
alert('执行了fn1方法');
};

index2.js

var num2=222;

function fn2(){
alert('执行了fn2方法');
};

index3.js

var num3=333;

function fn3(){
alert('执行了fn3方法');
};

index(自调用函数)

<body>
</body> <script type="text/javascript" src="student.js"></script>
<script type="text/javascript" src="superuser.js"></script> <script type="text/javascript"> var stu={
name:'张三',
age:20,
sex:'男孩子'
}; var stu1=new Student(stu);
alert(stu1.show()); </script>

student.js

//自调用函数
(function(){
/*
function Student(name,age,sex){
this.name=name;
this.age=age;
this.sex=sex;
};
*/ function Student(options){
options=options||{};
this.name=options.name||'学生';
this.age=options.age||18;
this.sex=options.sex||'女'; }; Student.prototype.show=function(){
return "name="+this.name+"\tage="+this.age+"\tsex="+this.sex;
}; //向外界暴露Student类的构造函数
window.Student=Student; })();

superuser.js

(function(){

    //超级管理员
function SuperUser(name,age,sex){
this.name=name;
this.age=age;
this.sex=sex;
}; SuperUser.prototype.show=function(){
return "name="+this.name+"\tage="+this.age+"\tsex="+this.sex;
};

随机生成方块

index.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<style type="text/css">
div{
height: 600px;
width:600px;
background-color: #C0C0C0;
}
</style>
</head> <body>
<div id="container">
</div>
</body> <script type="text/javascript" src="tools.js"></script>
<script type="text/javascript" src="box.js"></script>
<script type="text/javascript" src="main.js"></script> </html>

box.js

//自调用函数
(function(){ //新建一个Box类
function Box(map,options){
options=options||{};
this.height=options.height||20;
this.width=options.width||20;
this.x=options.x||0;
this.y=options.y||0;
this.backgroundColor=options.backgroundColor||'red'; //新建一个div标签
this.div=document.createElement('div');
map.appendChild(this.div);
this.map=map; //新建div的标签并且设置样式
this.init(); }; Box.prototype.init=function(){ var div=this.div;
//设置div的样式
div.style.backgroundColor=this.backgroundColor;
div.style.height=this.height+'px';
div.style.width=this.width+'px';
div.style.x=this.x+'px';
div.style.y=this.y+'px';
//让我们新建的格子脱离文档流
div.style.position='absolute'; //随机生成小格子的X轴和Y轴的坐标
this.Random(); }; Box.prototype.Random=function(){ this.div.style.left=Tools.getRandom(1,this.map.offsetWidth/this.width-1)*this.width+'px';
this.div.style.top=Tools.getRandom(1,this.map.offsetHeight/this.height-1)*this.height+'px';
var r=Tools.getRandom(0,255);
var g=Tools.getRandom(0,255);
var b=Tools.getRandom(0,255);
this.div.style.backgroundColor='rgb('+r+','+g+','+b+')'; } //对外暴露Box的构造函数
window.Box=Box; })();

main.js

(function(){

    var elements=[];
var container=document.getElementById('container');
for(var i=0;i<;i++){
var box=new Box(container);
elements.push(box);
}
setInterval(function(){ for(var i=0;i<elements.length;i++){
elements[i].Random();
}
},1000); })();

tools.js

var Tools={
//随机生成[0,600]之间随机数整数
getRandom:function(min,max){
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min; //含最大值,含最小值
} };

案例:贪吃蛇

更新中。。。

因为后面蛇的死亡和删除没有做好,之后找时间补充完整。。。

 index.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<style type="text/css"> *{
margin: 0px;
padding: 0px;
}
#map{
height: 800px;
width: 800px;
background-color: #C0C0C0;
}
</style>
</head> <body>
<div id="map">
</div>
</body>
<script type="text/javascript" src="tools.js"></script>
<script type="text/javascript" src="food.js"></script>
<script type="text/javascript" src="snake.js"></script>
<script type="text/javascript" src="game.js"></script>
<script type="text/javascript" src="main.js"></script> </html>

food.js

(function(){

    //保存生成的食物的数组
var elements=[]; //新建食物类的构造函数
function Food(map,options){ options=options||{};
this.height=options.height||20;
this.width=options.width||20;
this.x=options.x||0;
this.y=options.y||0;
this.backgroundColor=options.backgroundColor||'red'; //新建一个食物div
this.div=document.createElement('div');
map.appendChild(this.div);
this.map=map;
//将新建的食物存进食物数组中
elements.push(this.div); //渲染食物的样式
this.render();
} Food.prototype.render=function(){ this.div.style.height=this.height+'px';
this.div.style.width=this.width+'px';
this.div.style.backgroundColor=this.backgroundColor;
this.div.style.position='absolute';
this.random(map);
} //给食物随机生成坐标
Food.prototype.random=function(map){ this.div.style.left=Tools.getRandom(0,map.offsetWidth/this.width-1)*this.width+'px';
this.div.style.top=Tools.getRandom(0,map.offsetHeight/this.height-1)*this.height+'px'; }; //删除食物数组中之前生成的食物
function remove(){
for(var i=elements.length-1;i>=0;i--){
elements.splice(elements[i],1);
}
} //对外暴露食物类的构造函数
window.Food=Food; })();

game.js

(function(){

    //控制整个游戏执行的逻辑
function Game(map){
this.food=new Food(map);
this.snake=new Snake(map);
} Game.prototype.start=function(){ //将食物和蛇渲染进地图中
this.food.render(this.map);
this.snake.render(this.map); //让整个蛇按照方向移动
//一旦触碰到墙壁游戏结束
//一旦吃到食物,蛇节部分就要增加一节 }; window.Game=Game; })();

main.js

var map=document.getElementById('map');
var game=new Game(map);
game.start();

snake.js

(function(){

    //保存蛇的数组
var elements=[];
function Snake(map,options){ options=options||{};
this.height=options.height||20;
this.width=options.width||20;
//保存蛇的主体部分
this.body=[
{x:3,y:2,color:'red'},
{x:2,y:2,color:'blue'},
{x:1,y:2,color:'blue'},
];
this.map=map; //将蛇渲染进地图map
this.render();
} Snake.prototype.render=function(){
for(var i=0;i<this.body.length;i++){
var div=document.createElement('div');
this.map.appendChild(div);
//将蛇的部分保存到elements数组中
elements.push(div);
div.style.height=this.height+'px';
div.style.width=this.width+'px';
div.style.position='absolute';
div.style.left=this.body[i].x*this.width+'px';
div.style.top=this.body[i].y*this.height+'px';
div.style.backgroundColor=this.body[i].color; } }; //对外暴露蛇的构造函数
window.Snake=Snake; })();

tools.js

var Tools={
//随机生成[0,600]之间随机数整数
getRandom:function(min,max){
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min; //含最大值,含最小值
} };

前端学习:JS(面向对象)代码笔记的更多相关文章

  1. 原生js日历选择器,学习js面向对象开发日历插件

    在web开发过程中经常会碰到需要选择日期的功能,一般的操作都是在文本框点击,然后弹出日历选择框,直接选择日期就可以在文本框显示选择的日期.开发好之后给用户使用是很方便,但如果每一个日历选择器都要临时开 ...

  2. js 面向对象代码

    贴上一段同事写的代码,值的纪念 <script type="text/javascript"> //创建箱子类 function Box(option) { var s ...

  3. 适合前端学习JS的网站

    https://developer.mozilla.org/zh-CN/docs/Web/JavaScript

  4. js常用代码-笔记

    1.字符串截取substr(str,length)返回从指定位置开始,截取length长度的子字符串.substring(start,end)返回从start开始到end结束的字符串.end不写就到结 ...

  5. 前端学习:JS面向对象知识学习(图解)

    前端学习:JS面向对象知识学习(图解) 前端学习:JS(面向对象)代码笔记 JS面向对象图解知识全览 创建类和对象 方式1:使用Object()函数 方式2:使用自变量 方式3:使用工厂函数 创建多个 ...

  6. 前端学习:JS学习总结(图解)

    前端学习:JS学习总结(图解) JS的代码笔记 JS比HTML和CSS的知识点要多的多,下面分几段来介绍其内容... 为了能让大家更好的检索,前面的图解是整个JS的概括,后面的才是知识点... 旁边就 ...

  7. SpringMVC学习系列-后记 结合SpringMVC和Hibernate-validator,根据后台验证规则自动生成前台的js验证代码

    在SpringMVC学习系列(6) 之 数据验证中我们已经学习了如何结合Hibernate-validator进行后台的数据合法性验证,但是通常来说后台验证只是第二道保险,为了更好的用户体验会现在前端 ...

  8. 前端学习数据库MYSQL

    这篇文章主要写了 1.数据库MYSQL 2.基本上会遇到的所有SQL语句 数据库可视化软件------Navicat 数据库里边存放的是表,表与表之间是有关联的,而且可以对表进行相关操作(增,删,改, ...

  9. vue—你必须知道的 js数据类型 前端学习 CSS 居中 事件委托和this 让js调试更简单—console AMD && CMD 模式识别课程笔记(一) web攻击 web安全之XSS JSONP && CORS css 定位 react小结

    vue—你必须知道的   目录 更多总结 猛戳这里 属性与方法 语法 计算属性 特殊属性 vue 样式绑定 vue事件处理器 表单控件绑定 父子组件通信 过渡效果 vue经验总结 javascript ...

随机推荐

  1. docker操作命令大全和后台参数

    一.命令行 可以通过运行 docker ,或者 docker help 命令得到命令行的帮助信息(我们以 CentOS 为操作环境为例): [root@iz2ze2bn5x2wqxdeq65wlpz ...

  2. VS2010 报错该文件包含不能在当前代码页(936)中表示的字符。请将该文件保存为 Unicode 格式以防止数据丢失

    尤其代码是从linux平台复制过来: 报错如图: 更有甚者基本函数都报错: 当下检查发现if else break case等基本函数并无问题时,报错行数明显不一致等一定要注意文档编码格式, 最简单的 ...

  3. python类模拟电路实现

    实现电路: 实现方法: class LogicGate(object): def __init__(self, n): self.name = n self.output = None def get ...

  4. AutoresizingMask 的使用

    (1)先了解一下这几个枚举值的含义: (2)代码演说: 在viewcontroller 用代码创建一个红色的view,如下: UIView *redView = [[UIView alloc] ini ...

  5. iOS中Category和Extension 原理详解

    (一)Category .什么是Category? category是Objective-C .0之后添加的语言特性,别人口中的分类.类别其实都是指的category.category的主要作用是为已 ...

  6. Jmeter对服务器进行压力测试

    一.插件准备 下载地址:https://jmeter-plugins.org/downloads/all/ 1.下载插件管理: 2.将管理插件放到jmeter/../ext文件夹中 3.在插件管理中搜 ...

  7. 获得用户的真实ip HTTP_X_FORWARDED_FOR

    工作中经常会有有获得用户真实ip的情况,HTTP_X_FORWARDED_FOR总是忘记,所以我这里记录下来吧. 在PHP 中使用 [“REMOTE_ADDR”] 来取得客户端的 IP 地址,但如果客 ...

  8. 【原创】Talend 配置SSL支持gitlab

    背景 talend的源代码控制用的是gitlab,以前都是http方式的,但是最近突然改了https,所以talend登录失败,必须要SSL方式才能获取到分支等数据,才能提交代码. 证书导入 1.ta ...

  9. LaTeX安装与编译中文

    首先,感谢博客园团队帮我找回这篇被我误删除的博客.找回方法:发送邮件至"contact@cnblogs.com",然后就可以在工作人员的帮助下找回了.下面介绍LaTeX的安装并使其 ...

  10. C++和C的相互调用

    C++和C相互调用实际工程中C++和C代码相互调用是不可避免的C++编译器能够兼容C语言的编译方式C++编译器会优先使用C++编译的方式extern关键字能强制让C++编译器进行C方式的编译 exte ...