JS创建对象

JS创建对象,首先要明白JS和JAVA不一样,没有类的概念,所有对象都是实例。

只要把对象的__proto__属性,指向一个对象,就继承了该对象。
var Student = {
name: 'Robot',
height: 1.2,
run: function () {
console.log(this.name + ' is running...');
}
};
var xiaoming = {
name: '小明'
};
xiaoming.__proto__ = Student;
在编写JavaScript代码时,不要直接用obj.__proto__去改变一个对象的原型

Object.create()方法可以传入一个原型对象,并创建一个基于该原型的新对象,但是新对象什么属性都没有,因此,我们可以编写一个函数来创建xiaoming:

// 原型对象:
var Student = {
name: 'Robot',
height: 1.2,
run: function () {
console.log(this.name + ' is running...');
}
};
function createStudent(name) {
// 基于Student原型创建一个新对象:
var s = Object.create(Student);
// 初始化新对象:
s.name = name;
return s;
}
var xiaoming = createStudent('小明');
xiaoming.run(); // 小明 is running...
xiaoming.__proto__ === Student; // true
利用原型链创建对象。

javascript为每个创建的对象,都会设置一个原型,指向它的原型对象。JS在创建对象(不论是普通对象还是函数对象)的时候,都有一个叫做proto的内置属性,用于指向创建它的函数对象的原型对象prototype。

function Student(name) {
this.name = name;
}
Student.prototype.hello = function () {
alert('Hello, ' + this.name + '!');
};
function PrimaryStudent(props){
Student.call(this,props);//执行Student()构造方法,执行上下文用的是PrimaryStudent的,传入的参数也是PrimaryStudent里面的参数。
this.grade=props.grade || 1;
}
function F(){
}
F.prototype = Student.prototype;//把F的原型设置为student的原型对象
var f=new F();//相当于生成一个student实例,因为F此时的原型对象的constructor属性指向是Student对象。
PrimaryStudent.prototype = f;//把PrimaryStudent的原型设置为对象f,因为f对象就是Student对象
f.constructor = PrimaryStudent.constructor;
/*F对象只是个过渡的对象*/

继承动作可以封装为一个函数。。

function inherits(Child,Parent){
function F(){};
F.prototype=Parent.prototype;
var f = new F();
Child.prototype=f;
f.constructor = Child;
}
inherits(PrimaryStudent,Student);