一、使用函数创建对象
直接使用函数写对象,函数里面的this指针指向的是window。 es5中没有class类的体现,有function,es6中才出现了class类。向后端靠拢。 那么,es5中没有class类,怎么去创建对象?
function peope ( ) {
this . name = "" ;
this . age = "" ;
this . sex = "" ;
this . sleep = function ( ) {
return "睡觉" ;
} ;
this . eat = function ( ) {
return "吃饭" ;
} ;
}
peope ( ) ;
如果这样使用,this指向的是window 那么怎么用函数创建一个新对象? 使用new关键字 指向window。 people就是当前类的构造函数。 实例对象的原型链 = 函数的原型对象 原型对象的构造指向本身
var xiaoming = new people ( ) ;
console. log ( xiaoming) ;
console. log ( xiaoming. sleep ( ) ) ;
console. log ( xiaoming. __proto__ == people. prototype) ;
console. log ( people. prototype. constructor == people) ;
二、new实例化原理
new对象这个过程在做什么? new这个关键字,帮助我们创建一个对象,接入对象的引用。 自己构建一个new出来
function people ( ) {
this . name = "" ;
this . age = "" ;
this . sex = "" ;
this . sleep = function ( ) {
return "睡觉" ;
} ;
this . eat = function ( ) {
return "吃饭" ;
} ;
}
var New = function ( o ) {
var obj = { } ;
obj. __proto__ = o. prototype;
o. prototype. constructor = o;
return obj;
}
var maodou = New ( people) ;
console. log ( maodou) ;
var obj = { } ;
console. log ( obj) ;
var o = new Object ( ) ;
console. log ( o) ;
function Person ( name, age, sex ) {
this . name= name|| "" ;
this . age= age|| "" ;
this . sex= sex|| "" ;
}
Person . prototype. eat = function ( ) {
return this . name+ "吃饭" ;
}
Person . prototype. sleep = function ( ) {
return this . name+ "睡觉" ;
}
var New = function ( o ) {
var obj= { } ;
obj. __proto__= o. prototype;
o. prototype. constructor= o;
var args= Array . prototype. slice . call ( arguments, 1 ) ;
o . apply ( obj, args) ;
return obj;
}
var stu= New ( Person, '小明' , 20 , '男' ) ;
console. log ( stu) ;
三、获取相关属性
< script>
function work ( name, age, sex ) {
this . name = "" ;
this . age = "" ;
this . sex = "" ;
this . sleep = function ( ) {
return "睡觉" ;
} ;
this . eat = function ( ) {
return "吃饭" ;
} ;
}
var w = new work ( '小黑' , 18 , '男' ) ;
console. log ( w) ;
function people ( name, age, sex ) {
this . name = "" ;
this . age = "" ;
this . sex = "" ;
this . sleep = function ( ) {
return "睡觉" ;
} ;
this . eat = function ( ) {
return "吃饭" ;
} ;
}
var New = function ( o ) {
var obj = { } ;
obj. __proto__ = o. prototype;
o. prototype. constructor = o;
var args = Array . prototype. slice . call ( arguments, 1 ) ;
o . apply ( obj, args) ;
return obj;
}
var maodou = New ( people, "maodou" , 20 , "男" ) ;
console. log ( maodou) ;
< / script>
数组截取
var arr = [ 1 , 2 , 3 , 4 , 5 ] ;
console. log ( Array . prototype. splice . apply ( arr, [ 3 , 1 ] ) ) ;
自己写一个排序,使用数组来执行
Array . prototype. mySort = function ( ) {
return this . sort ( ) ;
} ;
var str = [ 2 , 3 , 1 , 4 ] ;
str. mySort ( ) ;
console. log ( str) ;