window.onload = function(){ //字面量方式创建
var obj = {
name:'如花',
age:22,
run:function(){
alert(this.name);
}
}
console.log(obj.name,obj.age);
obj.run();
};
//实列创建
var box = new Object();
box.name = 'ujiuye';
box.age = 18;
box.run = function(){
console.log(this.name);
return this.name + this.age;
}
console.log(box.run());
//工厂模式创建对象
function createObject(name,age){
var obj = new Object();
obj.name = name;
obj.age = age;
obj.run = function(){
return this.name + this.age;
}
return obj;
}
var box1 = createObject('Lee',100);
var box2 = createObject('jack',200);
alert(box1.run());
alert(box2.run());
//构造函数创建对象
function Ou(name){
this.name = name;
this.eat = function(){
console.log('吃饭了');
}
}
var s1 = new Ou('mm');
var s2 = new Ou('qiqi');
console.log(s1 instanceof Ou);
console.log(s1.eat == s2.eat);
//原型创建对象
function Str(){};
Str.prototype.name = '小明';
Str.prototype.sex = 'male';
Str.prototype.run = function(){
console.log('我是一个函数');
}
var obj = new Str();
console.log(obj.name);
var obj1 = new Str();
console.log(obj.name);
console.log(obj.run == obj1.run);
混合模式创建(构造+原型)
window.onload = function () {
//混合模式 构造函数+原型
//构造函数写可变的属性和变量
function Student(name) {
this.name = name;
this.eat = 18;
}
//破坏了封装性
Student.prototype.eat = function () {
console.log("吃饭");
};
//实例对象
var s1 = new Student("小明");
var s2 = new Student("如花");
console.log(s1.name,s2.name); //小明 如花
console.log(s1.eat == s2.eat); //true;
}
动态混合模式
window.onload = function () {
//混合模式 构造函数+原型
//构造函数写可变的属性和变量
function Student(name) {
this.name = name;
this.eat = 18;
/*Student.prototype.eat = function () {
console.log("吃饭");
} 调试还是每创建一个对象就会执行一次,原型是只初始化一次的*/
//判断是否存在,不存在则添加
if (!(typeof this.eat == "function")) {
Student.prototype.eat = function () {
console.log("吃饭");
}
}
//实例对象
var s1 = new Student("小明");
var s2 = new Student("如花");
console.log(s1.name, s2.name); //小明 如花
console.log(s1.eat == s2.eat); //true;
}
}
js面向对象,7种创建方式
最新推荐文章于 2023-02-01 17:34:00 发布