美文网首页
前端知识点(14)

前端知识点(14)

作者: 爱抽烟的臭屁虫 | 来源:发表于2019-06-14 10:35 被阅读0次

单体创建对象

var Tom = {

// 属性

name:'tom',

age:18,

// 方法

showName:function(){

alert(this.name);

},

showAge:function(){

alert(this.age);

}

}

//调用属性

alert(Tom.name);

alert(Tom.age);

//调用方法

Tom.showName();


工厂模式创建对象

创建一个空对象

var o = new object();方式一

var 0 ={};方式二

o.name = name;

o.age = age;

o.job = job;

o.showName = function(){

alert(this.name);

}

o.showAge = function(){

alert(this.age);

}

o.showJob = function(){

alert(this.job);

}

return o;

}

var Tom = Person('tom',18,'程序猿');

Tom.showJob();

var Jack = Person('jack',19,'攻城狮');

Jack.showJob();


构造函数

function Person(name,age,job){

this.name = name;

this.age = age;

this.job = job;

this.showName = function(){

alert(this.name);

}

this.showAge = function(){

alert(this.age);

}

this.showJob = function(){

alert(this.job);

}

}

//new的作用就相当于工厂模式中最开始创建了一个空对象,最后把对象返回

var Bob = new Person('bob',18,'产品汪');

Bob.showJob();

var Alex = new Person('alex',19,'运营喵');

Alex.showJob();

alert(Bob.showName == Alex.showName);//false


原型模式

function Person(name,age,job){

this.name = name;

this.age = age;

this.job = job;

Person.prototype.showName = function(){

alert(this.name);

}

Person.prototype.showAge = function(){

alert(this.age);

}

Person.prototype.showJob = function(){

alert(this.job);

}

}

//先去自己的对象中找showName函数,再去构造函数的原型找

var Lucy = new Person('lucy',18,'测试鼠');

//重写自身对象中的方法,不会影响其它对象

Lucy.showName = function(){

alert('我的名字是' + this.name);

}

Lucy.showName();//我的名字是lucy

var Lily = new Person('lily',19,'市场鸡');

Lily.showName();//lily

alert(Lucy.showName == Lily.showName);//false


call和apply

call和apply的区别

二者都可以改变当前的this,区别在于apply方法要将参数放入数组中再传参


相关文章

网友评论

      本文标题:前端知识点(14)

      本文链接:https://www.haomeiwen.com/subject/lzwyfctx.html