We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
let person = new Object({ name: '小花', age: 20 })
let person = { name: '小花', age: 20 }
function Person() { this.name = ’小花‘ this.age = 20 } let person = new Person()
let person = Object.create({ name: ’小花‘, age: 20 })
代码实现new 运算符
var newFn = function(fn, ...args) { // 创建一个空对象,并继承构造函数的原型对象 let obj = Object.create(fn.prototype) // this指向新创建的空对象,并执行构造函数中的代码 let temp = fn.apply(obj, args) // 返回新创建的对象 if (typeof temp === 'function') { return temp } else { return obj } }
function Person(name, age) { this.name = name || '小花' this.age = age || 20 } Person.prototype.speak = function() { console.log('Hi:' + this.name) } let p = newFn(Person,'xiaohua',20) console.log(p.name) // xiaohua p.speak() // Hi:xiahua
The text was updated successfully, but these errors were encountered:
No branches or pull requests
一. 创建对象的几种方式
1. 字面量创建对象
2. 构造函数创建对象
3. Object.create() 创建对象
二. new 运算符背后的执行过程
1. 创建一个新对象,并继承该构造函数的原型对象;
2. 上下文ths指向新对象,同时执行构造函数中的代码;
注意:如果参数为空,则 new F() 等价于 new F
3. 若构造函数没有返回对象,new 出来的结果即为步骤1 创建的新对象;若构造函数返回一个对象,这个对象取代new 出来的结果。
代码实现new 运算符
验证
The text was updated successfully, but these errors were encountered: