<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Document</title>
<style type="text/css">
botton{
width: 60px;
height: 30px;
line-height: 30px;
text-align: center;
display: block;
background-color: #81858d;
color: #FFFFFF;
border-radius:5px ;
}
</style>
</head>
<body>
<botton class="btn">计数!</botton>
<p class="pcoun">0</p>
<script type="text/javascript">
// 函数作为方法的调用
var myfonc = {
firstName:"zhangsan",
lastName :"lisi",
fullName:function(){
return this;
}
}
console.log(myfonc.fullName());
// 构造函数:
function myFunction(arg1, arg2) {
this.firstName = arg1;
this.lastName = arg2;
}
// 此处一定要new出来,对象才可以被调用
var x = new myFunction('11','222');
console.log(x.firstName+" "+x.lastName);
// 一个小的计算
var counte = 0;
function add(){
return counte +=1;
}
document.getElementsByClassName("btn")[0].onclick=function(){
document.getElementsByClassName('pcoun')[0].innerHTML = add();
}
/*
* 面向对象
* new出来的对象都是空白的,所以需要自己添加属性
*/
// 1.通过Object创建简单对象:
var obj = new Object();
// 为改对象添加属性
obj.name ="zhansan";
obj.age = 15;
/*
* 为该对象添加方法
* 方法就是一个函数,所以调用这个函数只需obj.showName();
*/
obj.showName = function(){
console.log("姓名:"+this.name)
}
obj.showage = function(){
console.log("年龄:"+this.age)
}
// 调用对象的方法
obj.showage()
obj.showName();
/*
* 2.用工厂方式来构造对象:工厂,简单来说就是投入原料、加工、出厂。
* 通过构造函数来生成对象,将重复的代码提取到一个函数里面,
* 避免像第一种方式写大量重复的代码。这样我们在需要这个对象的时候,就可以简单地创建出来了。
*/
// 1、构造函数
function createPerson(name,age){
// 创建对象
var person = new Object();
// 添加原料
person.name = name;
person.age = age;
// 加工原料
person.showname = function(){
console.log(this.name)
}
person.showage = function(){
console.log(this.age)
}
return person;
}
var wang = createPerson('wanger',55);
wang.showname();
</script>
</body>
</html>
转载于:https://my.oschina.net/u/3803573/blog/3041399