javascript - 改变函数的值还是与原型(prototype)保持一致?

标签 javascript function object parameters arguments

如果设置了参数而不是如果设置了参数如何更改对象的值

例子:

//parameter is a object
var Main = function(parameter)
{
    this.num = 1;
    this.string = "this"
}

Main.prototype.constructor = Main;

//source is an object
Main.prototype.copy = function(source)
{
    Main.prototype.copy.call(this, source);

    this.num = source.num;
    this.string = source.string;


    return this;
}

//set sub2 to have num is 4 instead of 1
var sub2 = new Main({num:4});

我想知道如何设置一个原型(prototype),如果参数为 et,则允许更改原始对象,但如果未设置参数,则使用 Main 函数的默认值,或者我会使用函数来设置如果参数为空则设置为默认值,如果为空则设置为参数对象?

谢谢

最佳答案

唯一的区别在于命名:

// So if you declare object as
var obj1 = {param1: "value1"};

// there is absolutely no difference if you declare it as
var obj2 = new Object({param2: "value2"});

// Its because every object inherits from Object,
// no matter which way is defined.

// Test
console.log(typeof obj1);
console.log(typeof obj2);

console.log(obj1 instanceof Object);
console.log(obj2 instanceof Object);

// Reaction to your comment below:
// Its as complicated as confusing. In this case 'var obj = {}' you are
// creating object and curly brackets delimit object definition.
// But in this case 'var obj2 = function() {}' you are creating function
// and curly brackets represents 'code block', not object literal.
// But ... function is object also...

var myFunction = function() {};
console.log(myFunction instanceof Object);

// And while this 'var obj = function(){para: 1}' is valid but meaningless 
// code, this 'var obj = function(){this.para: 1}' is as valid as 
// well as frequently used expression to create ... object. But object in 
// another sense... Its really confusing.

但是第一个表达式,它被称为“对象字面量表达式”,是创建对象的首选且安全的方法。因为一些恶意代码可以覆盖对象行为。因此,如果您将对象创建为 new Object(),您可能会创建一些意想不到的东西。但是不能覆盖对象文字表达式。

关于javascript - 改变函数的值还是与原型(prototype)保持一致?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39409460/

相关文章:

java - 接口(interface)方法如何在没有主体定义的情况下执行 Java 中的功能?

javascript - jQuery:如何在循环中附加数组项?

Javascript - 缺少输入的文本区域上的红色轮廓

php - 是否有一个 PHP 函数可以在不切割单词的情况下将字符串切割成多个部分?

php - 使用同一类中的函数

javascript - 如何调用 Meteor.methods 中的函数并返回值

c++ - 'DrawObject' 未在此范围内声明错误,使用 std::vector,尝试存储类对象 (c++)

php - 我怎样才能在 php 中实现这一点?

javascript - 在Javascript中。我如何判断对象中是否存在字段?

javascript - 在 angularjs 中添加非作用域变量的监视