Javascript 中的原型和继承
Prototypes and inheritance in Javascript
当我们使用如下两种不同的方式声明一个对象时,有什么区别?
var x = {}
和
var x = function () {}
var x = {}
以 Object
作为其原型创建一个对象的实例。
var x = function () {}
创建一个 "constructor function",当使用关键字 new
调用时 returns 一个以 Object
为原型的对象的新实例,但函数为constructor
属性.
的值
两者都可用于继承目的,{}
可与 Object.create()
一起使用,构造函数可与 new
一起使用。
var x1 = {prop:"test"}; // Object that inherits from Object
var x2 = Object.create(x1); // Make new object that inherits from x1
console.log(x2.prop);
// ********************************************************************
// Constructor function that inherits from Object
function y1() {
// Create instance property
this.otherProp = "Other value";
}
// Constructor function that will inherit from y1
function y2(){
// Ensure that the inherited object's constructor gets called
y1.prototype.constructor.call(this);
}
// Make y2 inherit from y1
y2.prototype = y1;
// Reset the constructor to correctly make instances
y2.prototype.constructor = new y2();
// Make an instance of the inherited object and test
var inheritedY = new y2();
console.log(inheritedY.otherProp);
创建一个 "constructor function",当使用关键字 new
调用时 returns 一个以 Object
为原型的对象的新实例,但函数为constructor
属性.
的值
两者都可用于继承目的,{}
可与 Object.create()
一起使用,构造函数可与 new
一起使用。
当我们使用如下两种不同的方式声明一个对象时,有什么区别?
var x = {}
和
var x = function () {}
var x = {}
以 Object
作为其原型创建一个对象的实例。
var x = function () {}
创建一个 "constructor function",当使用关键字 new
调用时 returns 一个以 Object
为原型的对象的新实例,但函数为constructor
属性.
两者都可用于继承目的,{}
可与 Object.create()
一起使用,构造函数可与 new
一起使用。
var x1 = {prop:"test"}; // Object that inherits from Object
var x2 = Object.create(x1); // Make new object that inherits from x1
console.log(x2.prop);
// ********************************************************************
// Constructor function that inherits from Object
function y1() {
// Create instance property
this.otherProp = "Other value";
}
// Constructor function that will inherit from y1
function y2(){
// Ensure that the inherited object's constructor gets called
y1.prototype.constructor.call(this);
}
// Make y2 inherit from y1
y2.prototype = y1;
// Reset the constructor to correctly make instances
y2.prototype.constructor = new y2();
// Make an instance of the inherited object and test
var inheritedY = new y2();
console.log(inheritedY.otherProp);
创建一个 "constructor function",当使用关键字 new
调用时 returns 一个以 Object
为原型的对象的新实例,但函数为constructor
属性.
两者都可用于继承目的,{}
可与 Object.create()
一起使用,构造函数可与 new
一起使用。