这里分两个版本将,ES5和ES6
一.ES5
1.JSON对象
var jsObject1 = JSON 这样定义的jsObject1已经是实例对象了,JSON对象创建的对象自动加了this引用:
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,运行作用域发生了变化,我们要在赋值前,对这个函数进行作用域绑定,用的是 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.创建对象
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关键字创建对象,初始化方式什么的与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'