版权声明:转发博客 请注明出处 否则必究 https://blog.csdn.net/lucky541788/article/details/82109271
构造函数约定( 首字母大写 )
1、(注:此方法渐渐淘汰了)
//创建构造函数
function Person(){
var obj=new Object();
//属性
obj.name=null;
obj.age=null;
obj.sex=null;
//方法
obj.play=function(){
console.log(this.name + '在玩');
};
obj.sleep=function(){
console.log(this.name + '在睡觉');
};
//返回
return obj;
}
//调用构造函数
var p=Person();
p.name='lucy';
p.age='18';
p.sex='girl';
console.log(p);//{name: "lucy", age: "18", sex: "girl", play: ƒ, sleep: ƒ}
p.play();//lucy在玩
2、(相比较1,可以清楚看出构造的是什么函数,且更加简易)
函数中的this:
this所在的函数在哪个对象中,this就代表这个对象
谁调用this就指代谁(例如:p.sayhi()中若调用this,则指代p)
构造函数中this,始终是new的当前对象
//创建构造函数
function Dog(json){
//属性
this.name=json.name;
this.age=json.age;
this.dogFriends=json.dogFriends;
//方法
this.eat=function(something){
console.log(this.name + '在吃' + something);
}
}
//调用构造函数
var smallDog=new Dog({name:'lucy',age:'18',dogFriends:'dd,xx'});
smallDog.age=5;//改值
console.log(smallDog);//Dog {name: "lucy", age: 5, dogFriends: "dd,xx", eat: ƒ}
smallDog.eat('奶');//lucy在吃奶
3、(推荐)
//创建构造函数
function Dog(json) {
this._init(json);
}
Dog.prototype = {
_init: function (json) {
this.name = json.name;
this.age = json.name;
this.dogFriends = json.dogFriends;
},
eat: function (something) {
console.log(this.name + '在吃' + something);
}
};
//调用构造函数
var smallDog=new Dog({name:'lucy',age:'18',dogFriends:'dd,xx'});
smallDog.age=5;//改值
console.log(smallDog);//Dog {name: "lucy", age: 5, dogFriends: "dd,xx", eat: ƒ}
smallDog.eat('奶');//lucy在吃奶
面向对象
var Dog=function(){
return new Dog.prototype.init();
};
Dog.prototype={//定义原型属性和方法
constructor:Dog, //指向Dog函数
//属性
init:function(){
this.name='lucy';
this.age='18';
},
//方法
about:function(){
console.log(this.name + '今年已经' + this.age + '了');
}
};
Dog.prototype.init.prototype=Dog.prototype;//右边黑色转换为红色指向线
var dog=new Dog();
dog.name='bob';//定义实例方法(bob代替了lucy)
dog.about();//bob今年已经18了
访问时,若是实例中有属性,则直接使用实例,否则找它的原型