[英]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.