iT邦幫忙

0

Javascript 之中的繼承問題

function a () { this.temp = 0; }
a.prototype = {_name: 'Eric',getName:function(){return this._name;} };
var c = new a();
此時 a.constructor point to Object.prototype.constructor
c.constructor === a //return false;
c instanceof a //return true;
我的疑問是 : 當我new這個物件時, 會執行參考到的constructor,而它的參考已經不是a() , 但這並不影響instance出來的物件?

圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 個回答

12
fillano
iT邦超人 1 級 ‧ 2013-12-08 22:22:06
最佳解答
<pre class="c" name="code">
var c = new a();

執行的不是a.constructor,而是a。

上面程式的執行過程(也就是new的過程)是:

  1. 將result設定為由a.prototype複製的物件
  2. 將result設定為a()執行時的this,執行a()
  3. 如果a()回傳一個物件,則將result設定為這個物件
  4. 回傳result,也就是assign給c

如果沒有執行a.prototype = {...},那c.constructor===a,如果執行了,那c.constructor===Object。

<pre class="c" name="code">
function a(){};
a.constructor === Function; //true
a.prototype.constructor === a; //true
var b = {};
b.constructor === Object; //true
a.prototype = b;
var c = new a;
c.constructor === Object; //true
john11221 iT邦新手 5 級 ‧ 2013-12-10 00:11:37 檢舉

謝謝回應, 3.如果a()回傳一個物件..有什麼情況會不回傳一個物件呢?

另外我想問的是

<pre class="c" name="code">
function a(){};
console.log(a.constructor === Function); //true
console.log(a.prototype.constructor === a);//true
  var b = [1,2,3];
//var b = {'0':1,'1':2,'2':3};
console.log(b.constructor === Object); //true
a.prototype = b;
var c = new a;
console.log(c.constructor === Object); //true
console.log(c.constructor);
console.log(c);

prototype 為 array 時 result 為 Object[1, 2, 3]
prototype 為 Object 時 result 為 Object { 0=1, 1=2, 2=3 }
如果我誤用的話,會造成任何結果上的錯誤嗎?

fillano iT邦超人 1 級 ‧ 2013-12-10 09:45:52 檢舉

我上面說的回傳一個物件,是指:

<pre class="c" name="code">
function a(name) {
    this.name = name;
    return {name: 'you fool'};
}
var b = new a('fillano');
console.log(b);//{name: 'you fool'}

通常不會有人這樣做,所以有把人認為這是個Wat...

fillano iT邦超人 1 級 ‧ 2013-12-10 10:11:12 檢舉

誤用...那應該難免會有錯誤吧...

Javascript大概是最自由的語言,什麼事情都可以做,所以你需要理解這個,然後小心使用。(我在FB看過有人評論說,當年Brenden Eich在netscape只花十天就做出這個語言,所以要盡量讓他有彈性之類的,不知道是不是Eich自己說的就是了XD)

你可以手動試試看:

<pre class="c" name="code">
var _alert = window.alert;
window.alert = window.confirm;
alert('test');

這樣,alert就變成confirm了。別忘記復原:

<pre class="c" name="code">
window.alert = _alert;

我要發表回答

立即登入回答