本节重点;文本框的输入
1.对象的调用
var person = {
name: "张飞",
age: 18,
sayHello: function () {
console.log(name + " 杀人")
}
}
person.sayHello();
对象的属性值可以是任何的数据类型,也可以是个函数。
如果一个函数作为一个对象的属性保存,那么我们称这个函数是这个对象的方法,调用这个函数就说调用对象的方法(method)。
注意:方法和函数只是名称上的区别,没有其它别的区
var person = {
name: "萧山",
age: 220,
sayName: function () {
console.log(this.name);
}
};
console.log(person);
2.this(使用),对象的简版本
构造函数:构造函数就是一个普通的函数,创建方式和普通函数没有区别,不同的是构造函数习惯上首字母大写,构造函数和普通函数的还有一个区别就是调用方式的不同,普通函数是直接调用,而构造函数需要使用new关键字来调用。
构造函数执行创建对象的过程:
调用构造函数,它会立刻创建一个新的对象
将新建的对象设置为函数中this,在构造函数中可以使用this来引用新建的对象
逐行执行函数中的代码
将新建的对象作为返回值返回(如下)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<script type="text/javascript">
//方法一
var student=new Object()
//设置对象
student.name="张飞"
student.stuID="19"
console.log(student)
//给对象设置函数
student.sayHello=function(){
console.log("大家好")
}
console.log(student)
//方法二
var qwe={
name:"超级玛丽",
age:"19",
lation:"江苏省南京市",
ady:function(){
console.log("扇浩")
}
}
qwe.ady()
qwe.lation
console.log(qwe.name,)
//方法三
//使用构造函数
function teacher(a,b){
this.a=a
this.b=b
this.eat=function(){
console.log("干饭")
}
}
//实例一个对象
var a1=new teacher("1","张飞")
a1.eat()
console.log(a1.a,a1.b)
console.log(a1)
</script>
</body>
</html>
在调用函数每次都会向函数内部传递进一个隐含的参数,这个隐含的参数就是this,this指向的是一个对象,这个对象我们称为函数执行的上下文对象,根据函数的调用方式的不同,this会指向不同的对象。
3.创建自定义对象
使用代码
解释(上面只是方法参数其中之一,用在查找,替换等等)
例题(小型计算机)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<input type="text" id="two" value="" /><br />
<input type="text" id="twe" value="" /><br />
<input type="button" name="" id="" value="+" onclick="call('+')" />
<input type="button" name="" id="" value="-" onclick="call('-')" />
<input type="button" name="" id="" value="*" onclick="call('*')" />
<input type="button" name="" id="" value="/" onclick="call('/')" /><br />
<input type="text" id="sum" value="" /> 运算结果
<script type="text/javascript">
function call(y) {
//获取文本框
//第一,二个文本框
var a = document.getElementById("two").value
var b = document.getElementById("twe").value
var sum
if (y == "+") {
sum = parseFloat(a) + parseFloat(b)
} else if (y == "-") {
sum = parseFloat(a) - parseFloat(b)
} else if (y == "*") {
sum = parseFloat(a) * parseFloat(b)
} else if (y == "/") {
sum = parseFloat(a) / parseFloat(b)
}
//总和
document.getElementById("sum").value = sum
}
</script>
</body>
</html>