簡體   English   中英

在 javascript 中返回某個值的函數上使用 new?

[英]Using new on a function that returns some value in javascript?

我正在嘗試繼承和創建對象,不知何故這讓我感到困惑。

a = function (){console.log("test"); return "hello"};
b = new a();
//console output
 test VM719:2
 a {}

這是什么意思 ? 這是否意味着 b 包含 a ? 如果是,那么如果我這樣做

console.log(b.a);
//console output 
 undefined
 undefined

為什么會這樣? 其次,如果我這樣做

b.__proto__
//console output 
 Object {}
a.prototype.test ="hello";
b.__proto__
//console output 
 Object {test: "hello"}

這很好,因為 new 會導致 bs 原型指向 a。

console.log(b);
//console output
 a {test: "hello"}

這個輸出是什么意思? 當我登錄 b.test 時,它給出“hello”,但當我登錄 ba 時,它給出“undefined”。那么 a 在輸出控制台中的意義是什么?

如果構造函數不返回任何內容、null 或任何原子/非對象值,則忽略該值並將新創建的對象引用返回給調用者。 所以你在控制台中看到你的對象的構造函數......

a {}手段是一個對象實例a ,因為你使用new創建一個實例。 在您的案例test ,該對象的屬性是與所有其他實例共享的prototype的屬性。 必須在構造函數中創建實例屬性,如下所示:

function A() {
  this.prop = 'hello';
}

A.prototype.test = function(){}; // shared with other instances

var b = new A();
b.prop; //=> 'hello' // unique to this instance

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM