估计不少作前端被面试的同窗总会被问到会不会oop开发,有些人一下蒙蔽了,什么oop。若是面试官说面向对象,或许你一下就明了了。前端
这个问题包含几个细节,es6
第一个是逼格(😄 )。面试
第二个是对象。函数
js中有六种数据类型,包括五种基本数据类型(Number,String,Boolean,Null,Undefined),和一种混合数据类型(Object)。oop
既然是面向对象,那确定是要有对象的( 😢 );requirejs
对象既有字面量对象和new 实例化对象; ui
var obj={ name:"weijueye", sayName:function(){ alert("姓名"+this.name+";性别"+this.sex); }, sex:'men' } obj.sayName(); //或者
var obj2={}; obj2.name='weijueye'; obj2.sayNmae=function(){ alert("姓名"+this.name+";性别"+this.sex); } obj2.sex='男'; obj2.sayNmae(); //或者 //1. value:值,默认是undefined
//2. writable:是不是只读property,默认是false,有点像C#中的const
//3. enumerable:是否能够被枚举(for in),默认false
//4. configurable:是否能够被删除,默认false
var obj3={} Object.defineProperties(obj3, { 'name': { value: 'weijueye', writable: true, enumerable: true, configurable: true }, sayName:{ value:function () { alert("姓名"+this.name+";性别"+this.sex); }, writable:false, configurable: false }, 'sex': { value: 'men', writable: false, enumerable: false, configurable: false } }); obj3.sayName(); // 或者利用函数直接返回一个函数
function Person(name,sex) { return { name:name, sayName:function(){ alert("姓名"+this.name+";性别"+this.sex); }, sex:sex } } Person('weijueye','men').sayName(); //实例化对象
function Person(name,sex) { var firstName='liu'; this.name=name; this.sex=sex; } Person.prototype.sayName=function(){ alert("姓名"+this.name+";性别"+this.sex); }; new Person('weijueye','men').sayName(); //在es6中终于能够用求之不得的类
class Person { //构造函数
constructor(name,sex){ var firstName='liu'; this.name=firstName+name; this.sex=sex; } //属性
sayName(){ setTimeout(()=>{ alert("姓名"+this.name+";性别"+this.sex); }, 1000); } } var person = new Person('weijueye','men') person.sayName();
面向对象开发的好处,减小全局变量污染;多人开发适用模块开发如 CMD下的seajs和AMD下requirejs,this
区别是cmd按需加载(我的推荐)amd是预加载spa
// AMD: define(["./a", "./b"], function(a, b) { //BEGIN if (true) { a.doSomething(); } else { b.doSomething(); } //END }); // CMD: define(function(require) { // BEGIN if(some_condition) { require('./a').doSomething(); } else { require('./b').soSomething(); } // END });