函数和对象使用方法
1.函数的声明:
语法:
function functionname() {
//执行的代码
}
实例:(函数声明不会立即执行,会在我们调用的时候执行)
function test(a,b) {
return a * b
}
调用:
test(1,2)
2.函数表达式:
语法:
var functionname = function() {
//执行的代码
}
实例:(函数表达式可以存储到变量中)
var name = function(a, b) {
return a * b
}
调用:
var b = name(1,2)
3.构造函数:(自定义构造函数是给对象添加属性,初始化属性用的)
语法/实例:
//构造函数的首字母大写
function Past(name,age) {
this.name = name;
this.age = age;
this.nameshow = function() {
alert(this.name)
}
}
调用:
//构造函数的调用方法 new
var past1 = new Past("lisi",20)
//构造函数中函数的使用
past1.nameshow()
var past2 = new Past("lisi",20)
past2.nameshow()
注意:
1) 构造函数的执行过程
1、Javascript对象
定义:对象只是带有属性和方法的特殊数据类型
属性:属性是与对象相关的值
方法:能够在对象上执行的动作
2.创建对象的方式
//使用同一接口创建多个对象时,会产生大量重复代码
var person = new Object();
person.name = 'lisi';
person.age = 22;
person.curriculum = ["mathematics","chinese","english"];
person.see = function() {
console.log(this.name)
}
//使用同一接口创建多个对象时,会产生大量重复代码
var person = {
name:"lisi",
age:22,
curriculum: ["mathematics","chinese","english"],
see:function() {
console.log(this.name)
}
}
//工厂模式解决了大量重复的问题,但是没有解决对象识别问题(即对象的类型都是object)
function createPerson(name, age, curriculum){
var o = new Object()
o.name = name;
o.age = age;
o.curriculum = curriculum;
o.see = function() {
console.log(this.name)
}
return o;
}
var person1 = createPerson("lisi", 22, ["mathematics","chinese","english"])
//instanceof无法判断它是谁的实例,只能判断他是对象,构造函数
var person2 = createPerson("wangwu",20,["physics","history","politics"])
//构造函数的首字母大写
function Past(name,age) {
this.name = name;
this.age = age;
this.nameshow = function() {
alert(this.name)
}
}
var past1 = new Past("lisi",20)
var past2 = new Past("lisi",20)
//1.使用new 关键字创建对象
//2.将构造函数的作用域给新的对象(this指向新的对象)
//3.在构造函数内使用this给新创建出来的对象添加成员
//4.返回新对象
function Person() {
}
Person.prototype.name = 'lisi';
Person.prototype.age = 22;
Person.prototype.curriculum = ["politics","english","mathematics"]
Person.prototype.see = function() {
console.log(this.name)
}
console.log(Person.prototype);//name:"lisi",age:22,curriculum:(3)
var person1 = new Person();
console.log(person1.name)
function Person(name,age) {
this.name = name;
this.age = age;
}
person.prototype = {
constructor:Person,
see:function() {
console.log(this.name)
}
}
var person1 = new Person("lisi",22)