和普通函数的区别
1.普通函数的调用方式:直接调用 person();
2.构造函数的调用方式:需要使用new关键字来调用 new Person();
这里的Person()既是函数名,也是这个对象的类名
构造函数书写方式有很多,比如:
一、
function Play(){
// 必须先自己构造一个函数,以后将这个函数名最为对象名
}
// 实例化函数
var p=new Play();
// 属性
p.width=300;
p.height=200;
p.num=4;
p.autotime=3;
// 方法
p.autoplay=function(){
alert("play....")
}
p.test=function(){
}
// 调用
alert(p.width);//300
p.autoplay(); //play...
二、
// 构造函数
function demo(){
// 获取
var p=new Object();
// 属性
p.width=300;
p.height=200;
p.num=4;
p.autotime=3;
// 方法
p.autoplay=function(){
alert("play....")
}
p.test=function(){
}
return p
}
var q=demo();
alert(q.width);
q.autoplay();
三、
function play(width,height,num){
// 有this就得有对象
this.width=width;
this.height=height;
this.num=num;
this.autoplay=function(){
alert("play...")
}
this.autotime=function(){
}
return this;
}
var obj=new play(300,200,3);
alert(obj.width);
obj.autoplay();
这三种方式通常用的比较多的是第三种。当然,还有一些别的书写方式
应用
一、
// 函数 实例化对象
function play(width,height,num){
this.width=width;
this.height=height;
this.num=num;
if(num<10){
this.autoplay=function(){
alert("参数的值为:" + this.num + " 小于10")
}
}else{
this.autoplay=function(){
alert("参数的值为:" + this.num + " 大于10")
}
}
this.autotime=function(){
}
return this;
}
var obj=new play(300,200,11); //实例化对象
// alert(obj.width);
obj.autoplay();
二、
<form>
<label>性别:</label>
男:<input type="radio" name="sex" id="" value="男" onclick="result()" />
女:<input type="radio" name="sex" id="" value="女" onclick="result()" />
</form>
<script>
function result() {
var xb = "";
var sex = document.getElementsByName("sex");
for (var i = 0; i < sex.length; i++) {
if (sex[i].checked) {
xb = sex[i].value;
}
break;
}
function play(width, height,num) {
this.width = width;
this.height = height;
this.num = num;
if (this.num == "男") {
this.autoplay = function() {
alert("条件成立")
}
} else {
this.autoplay = function() {
alert("条件不成立")
}
}
return this;
}
var p=new play(300,200,xb);
p.autoplay();
}