標籤:rip class 使用 而不是 logs const element blog 函數
對象
JavaScript 中的所有事物都是對象:字串、數值、數組、函數... 此外,JavaScript 允許自訂對象。
總之一句話,在javascript中一切都是對象。
//用new來建立對象var user = new Object(); //user也是一個對象 user.age = 37;//同時為user對象添加一個年齡的屬性 user.name = ‘周杰倫‘;
//用{}來建立一個對象 var user = { ‘name‘:‘周杰倫‘, ‘age‘:35 }
- Construction、prototype、__proto__
//constructor始終指向建立當前對象的建構函式。var arr = [];console.log(arr.constructor === Array); // truevar Foo = function() {};console.log(Foo.constructor === Function); // true// 由建構函式執行個體化一個obj對象var obj = new Foo();console.log(obj.constructor === Foo); // trueconsole.log(obj.constructor.constructor === Function); // true
//每個函數都有一個預設的屬性prototype,而這個prototype的constructor預設指向這個函數。function Person(name) { this.name = name;};Person.prototype.getName = function() { return this.name;};var p = new Person("jack");console.log(p.constructor === Person); // trueconsole.log(Person.prototype.constructor === Person); // trueconsole.log(p.constructor.prototype.constructor === Person); // true
//在這裡原型和原型鏈直接
這個是網上比較流傳的
下面這張是自己畫的
類的建立
雖然js是門基於對象的語言,但是沒有類這一概念的,雖然保留了class的關鍵字,但在ES6之前是無法使用的。所以,可以用建構函式類比類的建立,也就是偽類。所謂"建構函式",其實就是一個普通函數,但是內部使用了this變數。對建構函式使用new運算子,就能產生執行個體,並且this變數會綁定在執行個體對象上。每一個建構函式都有一個prototype屬性,指向另一個對象。這個對象的所有屬性和方法,都會被建構函式的執行個體繼承。這意味著,我們可以把那些不變的屬性和方法,直接定義在prototype對象上。
function User(){ this.name ; } //定義一個User的工作方法 User.prototype.work = function(){ alert(this.name+"工作中");}
var u1 = new User("周杰倫");
this關鍵字
this表示當前對象,如果在全域作用範圍內使用this,則指代當前頁面對象window; 如果在函數中使用this,則this指代什麼是根據運行時此函數在什麼對象上被調用。 我們還可以使用apply和call兩個全域方法來改變函數中this的具體指向。
console.log(this === window); //true 全域範圍內使用this指向window對象
function f(){ this.name = "jayChou"; // this在運行時指向window對象,在strict 模式下則是undefined}
var obj1 = { name: "jayChou", print: function(){ console.log(this.name); //this指向對象obj1,但是可以改變其指向 }};
new F(); // 函數內部的this指向新建立的對象。
var name = "jay";var person = { name : "jj", hello : function(a){ var sayhello = function(a) { console.log(this.name + " says " + a); }; sayhello(a); }}person.hello("hello world");//jay says hello world
另一種方式
var name = "jay";var person = { name : "jj", hello : function(a){ var that = this; var sayhello = function(a) { console.log(that.name + " says " + a); }; sayhello(a); }}person.hello("hello world");//jj says hello world
var ele = document.getElementById("id");ele.addEventListener(‘click‘,function(){ console.log(this); //this指向dom元素});
apply和call類似,只是後面的參數是通過一個數組傳入,而不是分開傳入。兩者都是將某個函數綁定到某個具體對象上使用,
自然此時的this會被顯式的設定為第一個參數。兩者的方法定義:call( thisArg [,arg1,arg2,… ] ); // 參數列表,arg1,arg2,...apply(thisArg [,argArray] ); // 參數數組,argArrayvar name = ‘global‘;var o = { name: ‘job‘, getName: function(){ console.log(this.name); }};o.getName(); // job//用call或apply改變函數中this的指向o.getName.call(this); // global
this的總結
當函數作為對象的方法調用時,this指向該對象。 當函數作為淡出函數調用時,this指向全域對象(strict 模式時,為undefined) 建構函式中的this指向新建立的對象 嵌套函數中的this不會繼承上層函數的this,如果需要,可以用一個變數儲存上層函數的this。
javascript OOP類與對象