CONNLY-J / cultivate

0 stars 0 forks source link

new #26

Open goldEli opened 4 years ago

goldEli commented 4 years ago
function Foo(name) {
  this.name = name
}

Foo.prototype.say = function(msg) {
  console.log(this.name + ": " + msg)
}

const a = new Foo("lily")

a.say("hello") // lily: hello

// 模拟 new 函数
function create(constructor, ...arg) {
  // code some stuff
}

const b = create(Foo, "Jack")

b.say("How are you") //Jack: How are you
CONNLY-J commented 4 years ago

(1)new是用来创建一个实例的,比如在下面的代码中,就以Foo为模板创建了一个新的对象,这个实例对象就继承了源对象的属性和方法。 (2)

function Foo(name) {
  this.name = name
}

Foo.prototype.say = function(msg) {
  console.log(this.name + ": " + msg)
}

const a = new Foo("lily")

a.say("hello") // lily: hello

// 模拟 new 函数
function create(constructor, ...arg) {
  // code some stuff
let obj = new Object();
obj.__proto__ = Object.creact(constructor.prototype);
var res = constructor.apply(obj,args);
return res instanceof Object?res:obj;
}

const b = create(Foo, "Jack")

b.say("How are you") //Jack: How are you