簡體   English   中英

是否可以使用文字表示法從對象繼承對象?

[英]is it possible to inherits object from object by using Literal notation way?

簡而言之:是否可以使用Literal notation從對象繼承對象,還是必須使用Constructor方法?

例如:(字面方式)

var obj = {}, obj2 = {};

obj.str = "hello world!";
obj.printTxt = function () {
    console.log(this.str);
};

obj2.prototype = obj.prototype; // occurs error message `(TypeError: obj2.printTxt is not a function)`
obj2.printTxt();

您的“文字符號”示例出現問題的根源是obj.prototype不存在。 對象沒有一個有意義的屬性,稱為prototype 對象與其原型之間的關系是不透明且不可變的-沒有確定原型的標准方法,也沒有在構建原型后對其進行更改的標准方法。

最接近的是ES5方法Object.create

var bar = {baz: []};
var foo = Object.create(bar);

在各方面都相當於

var foo, bar = {baz: []};
(function () {
    function Foo() {}
    Foo.prototype = bar;
    foo = new Foo;
})();

並創建一個對象foo其原型為(不透明且不可變) bar

暫無
暫無

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

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