js中创建对象的5种方法
Posted jswzy
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了js中创建对象的5种方法相关的知识,希望对你有一定的参考价值。
1、原始模式
var dog = { name: jack, length: 70, wang:function(){ console.log(this.name); }
2、工厂模式(批量)
function creatdog (name,length) { var moudle = new object (); dog.name=name; dog.length=length; dog.wang=function(){ console.log(this.name); }; return moudle; }
3、构造函数
function Dog (name,length) { this.name=name; this.length=length; this.wang=function() { console.log(this.name); }; } var dog1 = new Dog( ‘wangcai‘ , 80) //创建一个dog1对象 Dog(‘wangcai‘, 80); //属性方法都给window对象,window.name=‘wangcai‘,window.wang()会输出wangcai
4、原型模式
function Dog () {} Dog.prototype.name = ‘wangcai‘; Dog.prototype.length=80; Dog.prototype.wang= function () { console.log(this.name); }; var dog1 = new Dog();
// dog1:name:‘wangcai‘;length:80;f:wang()
5、混合模式
function Dog (name, length) { this.name = name; this.length = length; } Dog.prototype = { hobby: [‘running‘,‘eat‘]; wang: function () {
console.log(this.name);
} }; var dog1 = new Dog(‘wangcai‘, 80); //dog1:‘wangcai‘,80; __proto__: [‘running‘,‘eat‘],wang var dog2 = new Dog(‘defu‘, );70 //dog2:‘defu‘,70;__proto__: [‘running‘,‘eat‘],wang
以上是关于js中创建对象的5种方法的主要内容,如果未能解决你的问题,请参考以下文章