這里分兩個版本將,ES5和ES6
var jsObject1 = { objectName : 'jsObject1', objectClass : 'JSON', testPRop1 : 'testProp1', objectf1 : function(){ console.log(this.objectName); }, objectf2 : function(){ return this.objectClass; }, objectf3 : function(){ this.objectf1(); }}這里的實例對象jsObject1中有三個屬性和三個屬性方法,這里的所有屬性都已經自動加了this,所有對象內引用的時候要加this。jsObject1.objectf1(); //'jsObject1'console.log(jsObject1.objectf2()); //'JSON'jsObject1.objectf3(); //'jsObject1'function testf1(){ //這里testf1賦值給jsObject1的屬性,形成屬性方法 console.log(this.testProp1);}jsObject1.objectf4 = testf1;jsObject1.objectf4(); //‘testProp1’我們嘗試著輸出對象的屬性和調用對象的方法,并在后面向對象添加屬性方法testf1()。this這個東西,大體說就是,this有關的東西在哪里運行,就指向誰。2.函數對象
/*****構造函數******* 1.構造函數,用new關鍵字生成實例對象* 2.用this引用聲明的變量,實例對象可以訪問* 3.*/function jsObject2(name){ var object2Name = name; //局部變量,內部函數可以訪問 this.object2Class = 'han shu'; //局部變量,但是通過實例對象可以訪問 function of1(){ console.log(object2Name); } this.of2 = function(){ of1(); }}var js2 = new jsObject2('hello'); //實例化對象js2.of2(); //'hello'console.log(js2.object2Class); //'han shu'先定義函數,然后用new的方法,生成實例對象。3.JSON對象作用域綁定
/*****JSON對象作用域設置bind******* 1.在方法賦值等改變了方法作用的時候,需要bind綁定,這樣方法內引用的屬性才能正確賦值* 2.* 3.*/var jsObject3 = { objectName : 'jsObject3', onlyo3 : 'hello world o3', o3f1 : function(){ return this.onlyo3; }}var jsObject4 = { objectName : 'jsObject4', onlyo4 : 'hello world o4', o4f1 : function(){}, o4f2 : function(){ return this.o4f1(); }}var z = jsObject3.o3f1.bind(jsObject3); //綁定作用域jsObject4.o4f1 = z; console.log(jsObject4.o4f2()); //'hello world 03'我們這里將 jsObject3 的屬性方法 o3f1 賦值給了 jsObject4 的 o4f1,運行作用域發(fā)生了變化,我們要在賦值前,對這個函數進行作用域綁定,用的是 bind()方法。4.函數對象作用域綁定
/*****函數對象作用域設置bind******* 1.在方法賦值等改變了方法作用的時候,需要bind綁定,這樣方法內引用的屬性才能正確賦值* 2.* 3.*/function jsObject5(){ this.o5 = 'object 5'; this.o5f1 = function(){ return this.o5; }.bind(this); //綁定作用域}function jsOjbect6(){ this.o6f1 = function(){}; this.o6f2 = function(){ return this.o6f1() };}var testO5 = new jsObject5();var testO6 = new jsOjbect6();testO6.o6f1 = testO5.o5f1;console.log(testO6.o6f2()); //'object 5'二.ES6
1.創(chuàng)建對象
class object { constructor(name,version){ //構造函數,初始化用 this.name = name; this.version = version; this.test = 'hello world'; } of1(){ console.log(this.version); } of2(){ this.of1(); }}let obj = new object('chad','ES6');console.log(obj.name); //'chad'obj.of1(); //'ES6'obj.of2(); //'ES6'由于ES6的語法糖,讓我們用class關鍵字創(chuàng)建對象,初始化方式什么的與OC,C++有那么一絲神似了。2.作用域綁定
class ojbect1 { constructor(x,y){ this.x = x; this.y = y; this.o1f1 = this.o1f1.bind(this); } o1f1(){ return this.x; }}class object2 { constructor(){ } o2f1(){ } o2f2(){ return this.o2f1(); }}let testObject1 = new ojbect1('hello','world');let testObject2 = new object2();testObject2.o2f1 = testObject1.o1f1;console.log(testObject2.o2f2()); //'hello'
新聞熱點
疑難解答