var Student = {name: ‘Robot‘,height: 1.2,run: function () {console.log(this.name + ‘ is running...‘);}};var xiaoming = {name: ‘小明‘};xiaoming.__proto__ = Student;//xiaoming的原型指向了对象Student
// 原型对象: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
function Student(name) {this.name = name;this.hello = function () {alert(‘Hello, ‘ + this.name + ‘!‘);}}//这确实是一个普通函数,如果不写new的话;//如果写了new,它就是一个构造函数,默认返回this,不需要在最后写return this;var xiaoming = new Student(‘小明‘);xiaoming.name; // ‘小明‘xiaoming.hello(); // Hello, 小明!//这里的xiaoming原型就指向这个构造函数Student了
xiaoming.constructor === Student.prototype.constructor; // trueStudent.prototype.constructor === Student; // trueObject.getPrototypeOf(xiaoming) === Student.prototype; // truexiaoming instanceof Student; // true




var laoWang = {name: ‘隔壁老王‘,height: 1.2,run: function () {console.log(this.name + ‘ is running...‘);}};var xiaoming = {name: ‘小明‘};xiaoming.__proto__ = laoWang; //xiaoming的原型指向了对象Student //相当于告诉小明的爹是谁,比如小明的爹变成了老王xiaoming.run(); // 小明 is running... //小明没定义run方法也会使用run()了
function Student(name){this.name = name;this.run = function(){return this.name + "is running..."}}var xiaoming = new Student("xiaoming");var xiaohong = new Student("xiaohong");xiaoming.run === xiaohong.run;//false----------------------------------------------------------------------function Student(name){this.name = name;}Student.prototype.run = function(){return this.name + "is running..."}xiaoming = new Student("xiaoming");xiaohong = new Student("xiaohong");xiaoming.run === xiaohong.run;//true
function Student(props) {this.name = props.name || ‘匿名‘; // 默认值为‘匿名‘this.grade = props.grade || 1; // 默认值为1}Student.prototype.hello = function () {alert(‘Hello, ‘ + this.name + ‘!‘);};function createStudent(props) {return new Student(props || {})}
var xiaoming = createStudent({name: ‘小明‘});xiaoming.grade; // 1
04面向对象编程-01-创建对象 和 原型理解(prototype、__proto__)
原文:http://www.cnblogs.com/deng-cc/p/6642427.html